As the title explains, I'd like to add links to my TextView
, with these two caveats:
I want the link to act on a part of the TextView
, not the full one (something like an A
anchor in HTML).
I want the link to point to an action in my code, not a website. I could define a method in my activity, or implement an OnClickListener
, and execute that when that specific link is clicked.
So far, I succeeded to turn phone numbers, addresses, web sites and emails into dedicated external links using:
Linkify.addLinks(message, Linkify.ALL);
I'd like something similar for internal links (to my method), with the possibility to define custom ones.
Also, using a web page with internal link and a web view is not really an option, as I already have several complex layouts defined, and having to modify the whole application and concepts would be quite a pain...
Any idea?
EDIT: Kabuko gave me a very good solution, here is exactly how I implemented it:
final TextView descriptionTextView = (TextView) findViewById(R.id.description);
final Spannable span = Spannable.Factory.getInstance().newSpannable("the full text for the view");
span.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(StartEventActivity.this, "LINK CLICKED", Toast.LENGTH_SHORT).show();
}
}, 1, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // 1 and 20 to be replaced with actual index of start and end of the desired link
descriptionTextView.setText(span);
descriptionTextView.setMovementMethod(LinkMovementMethod.getInstance());
The target=”_blank” attribute is just set to open a new tab in the browser. In Android, the most common way to show a text is by TextView element. The whole text in the TextView is easy to make clickable implementing the onClick attribute or by setting an onClickListener to the TextView.
This example demonstrates how do I set the part of the Android textView as clickable. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
SpannableString string = new SpannableString("Text with clickable text"); string. setSpan(new CustomClickableSpan(), 10, 19, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE); Text with ClickableSpan .
android.text.method.LinkMovementMethod. A movement method that traverses links in the text buffer and scrolls if necessary. Supports clicking on links with DPad Center or Enter.
If you wanted to actually go to URLs you could use Html.fromHtml
, but if you want your own click handlers you can use a ClickableSpan
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With