linkify on textview with domain in text not working, links not clickable
Figured this out. for some reason i needed to wrap my text as character data using tag cData
in my strings
file. this works:
<string name="go_to_settings"><![CDATA[Please go to "Settings" in <a href="https://www.mywebsite.com/settings">mywebsite.com</a> to change this status :]]></string>
then the textview
looks like this:
<TextView
android:id="@+id/tv_instructions"
android:layout_width="280dp"
android:layout_height="wrap_content"
android:layout_marginTop="73dp"
android:lineSpacingExtra="3sp"
android:text="@string/go_to_settings"
android:textAlignment="center"
android:textColor="#5c5c5c"
android:textColorLink="@color/action_blue"/>
Java Code
tv_instructions.text=(utils.fromHTML(resources.getString(R.string.go_to_settings),null))
tv_instructions.movementMethod=LinkMovementMethod.getInstance()
How to make links in a TextView clickable
Buried in the API demos, I found the solution to my problem:
File Link.java:
// text2 has links specified by putting <a> tags in the string
// resource. By default these links will appear but not
// respond to user input. To make them active, you need to
// call setMovementMethod() on the TextView object.
TextView t2 = (TextView) findViewById(R.id.text2);
t2.setMovementMethod(LinkMovementMethod.getInstance());
I removed most of the attributes on my TextView to match what was in the demo.
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtCredits"/>
That solved it. It is pretty difficult to uncover and fix.
Important: Don't forget to remove autoLink="web"
if you are calling setMovementMethod()
.
Linkify in android TextView
I had problems with automatic links, so I turned it off and instead I am using html formating of the text plus this code:
TextView textView = (TextView) findViewById(R.id.TextBox);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(Html.fromHtml(strText));
An email link goes <a href="mailto:my@email.com">my@email.com</a>
Does Linkify work for TextView in Android?
Have clickable span and set the text with the clikable span. You can have custom color for the clickabke span. When you click on the text in textview it displays a toast.
String title="hello";
SpannableString ss1= new SpannableString(title);
ss1.setSpan(new MyClickableSpan(title), 0, ss1.length(), 0);
tv = (TextView) findViewById(R.id.textview);
tv.setText(ss1);
tv.setMovementMethod(LinkMovementMethod.getInstance());
MyClickableSpan
class MyClickableSpan extends ClickableSpan{
String clicked;
public MyClickableSpan(String string)
{
super();
clicked =string;
}
public void onClick(View tv)
{
// onclick of text in textview do something
Toast.makeText(MainActivity.this,clicked ,Toast.LENGTH_SHORT).show();
//display a toast
}
public void updateDrawState(TextPaint ds)
{
ds.setColor(Color.BLUE);//set text color
ds.setUnderlineText(true); // set to false to remove underline
}
}
Resulting Snap Shot
EDIT:
Open a browser with the url on click on text in textview. You can also pass the url to a activity. Retrieve the url and load the url in webview.
<uses-permission android:name="android.permission.INTERNET"/>
public void onClick(View tv) {
//do something
Toast.makeText(MainActivity.this,clicked ,
Toast.LENGTH_SHORT).show();
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
OR
In onClick()
Intent t= new Intent(MainActivity.this,SecondActivity.class);
t.putExtra("key","http://www.google.com");
startActivity(t);
second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/wv"></WebView>
</LinearLayout>
Then in SecondActivty
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
WebView wv= (WebView) findViewById(R.id.wv);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
wv.loadUrl(extras.getString("key"));
}
}
}
Linkify with Compose Text
In case someone is looking for a solution, the following will make any links clickable and styled in your text:
@Composable
fun LinkifyText(text: String, modifier: Modifier = Modifier) {
val uriHandler = LocalUriHandler.current
val layoutResult = remember {
mutableStateOf<TextLayoutResult?>(null)
}
val linksList = extractUrls(text)
val annotatedString = buildAnnotatedString {
append(text)
linksList.forEach {
addStyle(
style = SpanStyle(
color = Color.Companion.Blue,
textDecoration = TextDecoration.Underline
),
start = it.start,
end = it.end
)
addStringAnnotation(
tag = "URL",
annotation = it.url,
start = it.start,
end = it.end
)
}
}
Text(text = annotatedString, style = MaterialTheme.typography.body1, modifier = modifier.pointerInput(Unit) {
detectTapGestures { offsetPosition ->
layoutResult.value?.let {
val position = it.getOffsetForPosition(offsetPosition)
annotatedString.getStringAnnotations(position, position).firstOrNull()
?.let { result ->
if (result.tag == "URL") {
uriHandler.openUri(result.item)
}
}
}
}
},
onTextLayout = { layoutResult.value = it }
)
}
private val urlPattern: Pattern = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?\\-+()\\[\\]\\*$~@!:/{};']*)",
Pattern.CASE_INSENSITIVE or Pattern.MULTILINE or Pattern.DOTALL
)
fun extractUrls(text: String): List<LinkInfos> {
val matcher = urlPattern.matcher(text)
var matchStart: Int
var matchEnd: Int
val links = arrayListOf<LinkInfos>()
while (matcher.find()) {
matchStart = matcher.start(1)
matchEnd = matcher.end()
var url = text.substring(matchStart, matchEnd)
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "https://$url"
links.add(LinkInfos(url, matchStart, matchEnd))
}
return links
}
data class LinkInfos(
val url: String,
val start: Int,
val end: Int
)
Related Topics
How to Detect Device Is Android Phone or Android Tablet
Error: Status{Statuscode=Developer_Error, Resolution=Null}
Android Java Lang Runtimeexception Fail to Connect to Camera Service
Android Http Connection Exception
How to List Files in an Android Directory
How to Re-Sign an .Apk with a Different Certificate Than What It Came With
How to Get the Current Page Number of a Viewpager for Android
Scrollview Can Host Only One Direct Child
How to Scale Bitmap to Screen Size
Device Not Detected in Eclipse When Connected with Usb Cable
How to Get Current Flavor in Gradle
How to Share Same Data Between Multiple Activities
How to Always Run a Service in the Background
How to Make My Layout Scroll Both Horizontally and Vertically