在我的 android 应用程序中,我必须在 Textview 上显示标签。同一个 textView 中可以有多个标签,我想为每个标签添加点击事件。在同一个文本视图中可能还有一些其他文本。我怎样才能以这样的方式格式化文本,所有标签都可以点击粗体文本和其他文本作为普通文本。假设要在文本视图中设置文本“#tag1 text message #tag2 #tag3 normal text”,其中#tag1、#tag2 和#tag3 为粗体文本,其余文本为普通文本样式,那么我该如何实现呢。
提前致谢。
在我的 android 应用程序中,我必须在 Textview 上显示标签。同一个 textView 中可以有多个标签,我想为每个标签添加点击事件。在同一个文本视图中可能还有一些其他文本。我怎样才能以这样的方式格式化文本,所有标签都可以点击粗体文本和其他文本作为普通文本。假设要在文本视图中设置文本“#tag1 text message #tag2 #tag3 normal text”,其中#tag1、#tag2 和#tag3 为粗体文本,其余文本为普通文本样式,那么我该如何实现呢。
提前致谢。
你可以使用这样的东西,
String str = "<b> #tag1 </b> " + textMessage + "<b> #tag2 #tag3 </b>" + normalText;
your_textview.setText(Html.fromHtml(str));
您也可以尝试SpannableStringBuilder。
您可以尝试使用SpannableStringBuilder
SpannableStringBuilder 可以:
有关代码参考,您可以查看此帖子
private static void singleTextView(TextView textView, final String userName, String status, final String songName) {
SpannableStringBuilder spanText = new SpannableStringBuilder();
spanText.append(userName);
spanText.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
// On Click Action
}
@Override
public void updateDrawState(TextPaint textPaint) {
textPaint.setColor(textPaint.linkColor); // you can use custom color
textPaint.setUnderlineText(false); // this remove the underline
}
}, spanText.length() - userName.length(), spanText.length(), 0);
spanText.append(status);
spanText.append(songName);
spanText.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
// On Click Action
}
@Override
public void updateDrawState(TextPaint textPaint) {
textPaint.setColor(textPaint.linkColor); // you can use custom color
textPaint.setUnderlineText(false); // this remove the underline
}
},spanText.length() - songName.length(), spanText.length(), 0);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(spanText, TextView.BufferType.SPANNABLE);
}