I have a text with words that I like to be clickable in a textview.
I found this good rated answer here
The text elements look like links in the textview but the click-function does not get triggered.
my XML:
<TextView
android:id="@+id/mainTextView"
android:layout_width="0dp"
android:layout_height="193dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:clickable="true"
android:enabled="false"
android:linksClickable="true"
android:text="@string/main_text"
app:layout_constraintBottom_toTopOf="@+id/linearLayout2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
and here my code:
setTextViewHTML(lv_mainTextView, getResources().getString(R.string.main_text));
...
protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span)
{
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan clickable = new ClickableSpan() {
@Override
public void onClick(View view) {
// Do something with span.getURL() to handle the link click...
Toast.makeText(getApplicationContext(), "Click", Toast.LENGTH_LONG).show();
}
};
strBuilder.setSpan(clickable, start, end, flags);
strBuilder.removeSpan(span);
}
protected void setTextViewHTML(TextView text, String html)
{
CharSequence sequence = Html.fromHtml(html);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
for(URLSpan span : urls) {
makeLinkClickable(strBuilder, span);
}
text.setText(strBuilder);
text.setMovementMethod(LinkMovementMethod.getInstance());
}
When I debugged it the function "makeLinkClickable" is being called but onCLick is never triggered.
Any ideas and help would be appreciated!!!
Thanks Kev
EDITED:
My text in the resource Looks like that:
"The <a href="tree">tree</a> is larger than the <a href="flower">flower</a>"
Which gives me the following string when fetching it with fromHTML:
"The <a href="tree">tree</a> is larger than the <a href="flower">flower</a>"