如何在 TextView 的文本上设置多个跨度(可点击和粗体)

How to set multiple spans on a TextView's text (clickable and bold)

    mSpannableString = new SpannableString("12:00PM");

    mSpannableString.setSpan(clickableSpan, 0, 7, 0);
    mSpannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, 7, 0);

    TextView textView = new TextView(getContext());
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(mSpannableString);

    mCancelFrom.setText(getString(R.string.cancel_from_text) + " " + mSpannableString);

我需要将文本设置为粗体并使其可点击。上面的代码我已经写在一个对话框中。正在显示字符串“12:00PM”。但它没有大胆的效果,也不可点击。你能帮我解决这个问题吗?

试试这个,它可能对你有帮助

SpannableString ss = new SpannableString("12:00PM");
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            startActivity(new Intent(SendSMS.this, SendSMS.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(clickableSpan, 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    mCancelFrom.setText(getString(R.string.cancel_from_text) + " " + ss);

当你执行 mCancelFrom.setText(getString(R.string.cancel_from_text) + " " + mSpannableString);

执行: getString(R.string.cancel_from_text) + " " + mSpannableString

上述操作的结果是 "String" 因此框架调用 mSpannableString.toString 能够附加前两个字符串并且您丢失了跨度等

像这样(这几乎就是你的代码):

String tmp = getString(R.string.cancel_from_text) + " ";
mSpannableString = new SpannableString(tmp + "12:00PM");

mSpannableString.setSpan(clickableSpan, tmp.length(), mSpannableString.length(), 0);
mSpannableString.setSpan(new StyleSpan(Typeface.BOLD), tmp.length(), mSpannableString.length(), 0);

TextView textView = new TextView(getContext());
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(mSpannableString);