I have textview like this:
<TextView
android:id="@+id/tvComment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web" />
tvComment.setText(Html.fromHtml(message));
Here is my text:
<a href='myapp://293482'>Jack </a> http://google.com
The problem is that <a href>
not clickable. If I remove android:autoLink="web"
, it is clickable but the link http://google.com
does not work.
How can I make both of them clickable?
答案 0 :(得分:7)
请试试这个:
<强> XML 强>
<TextView
android:id="@+id/tvHello"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:linksClickable="true"
/>
<强>爪哇强>
@Override
protected void onCreate(Bundle savedInstanceState) {
{
...
String html = "<a href='myapp://293482'>Jack </a> http://google.com";
tvHello = (TextView) findViewById(R.id.tvHello);
tvHello.setText(linkifyHtml(html, Linkify.ALL));
tvHello.setMovementMethod(LinkMovementMethod.getInstance());
}
public static Spannable linkifyHtml(String html, int linkifyMask) {
Spanned text = Html.fromHtml(html);
URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class);
SpannableString buffer = new SpannableString(text);
Linkify.addLinks(buffer, linkifyMask);
for (URLSpan span : currentSpans) {
int end = text.getSpanEnd(span);
int start = text.getSpanStart(span);
buffer.setSpan(span, start, end, 0);
}
return buffer;
}
答案 1 :(得分:0)
根据 Linkify.addLinks
javadoc:
...它还删除了附加到 Spannable 的任何现有 URLSpans,以避免在同一文本上重复调用它时出现问题。
这是基于@nuuneoi 回答的 Kotlin 风格:
private fun String.toSpannableWithHtmlAndAutoLink() =
Html.fromHtml(this, Html.FROM_HTML_MODE_COMPACT).let { text ->
text.toSpannable().apply {
Linkify.addLinks(this, Linkify.ALL)
text.getSpans<URLSpan>().forEach {
setSpan(it, text.getSpanStart(it), text.getSpanEnd(it), text.getSpanFlags(it))
}
}
}
@BindingAdapter("textWithLinks")
fun setTextWithLinks(view: TextView, message: String?) = view.apply {
text = message?.toSpannableWithHtmlAndAutoLink()
movementMethod = LinkMovementMethod.getInstance()
}
答案 2 :(得分:0)
/**
* This method is used to set clickable part in text
* Don't forget to set android:textColorLink="@color/link" (click selector) and
* android:textColorHighlight="@color/window_background" (background color while clicks)
* in the TextView where you will use this.
*/
fun TextView.makeLinks(text: Spanned, conditionMatch: Boolean, action: () -> Unit) {
this.text = text
if (conditionMatch) {
val startIndex = text.lastIndexOf(Constants.COMMA)
val endIndex = text.lastIndexOf(Constants.DOT_DELIMITER)
this.movementMethod = LinkMovementMethod.getInstance()
this.setText(text, TextView.BufferType.SPANNABLE)
val clickableSpan: ClickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
action.invoke()
}
}
val mySpannable: Spannable? = this.text as Spannable?
mySpannable?.setSpan(clickableSpan, startIndex + Constants.NumericConstants.TWO, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}