美文网首页
同一个TextView不同文字的点击事件

同一个TextView不同文字的点击事件

作者: 我要棒棒糖 | 来源:发表于2021-06-24 09:01 被阅读0次
TextView mTextView2;
//在onCreate方法中找到赋值的控件
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test2);

    mTextView2 = (TextView)findViewById(R.id.text2);
    /*********** 同一个TextView不同文字的点击事件*******/
    StringBuilder actionText = new StringBuilder();
    actionText
            .append("我已阅读并同意"+"<a style=\"text-decoration:none;\" href='username'>"
                    + "《用户协议》" + " </a>");
    actionText
            .append("和"
                    + "<a style=\"color:blue;text-decoration:none;\" href='singstar'> "
                    + " 《隐私协议》" + "</a>");
    mTextView2.setText(Html.fromHtml(actionText.toString()));
    mTextView2.setMovementMethod(LinkMovementMethod
            .getInstance());
    CharSequence text = mTextView2.getText();
    int ends = text.length();
    Spannable spannable = (Spannable) mTextView2.getText();
    URLSpan[] urlspan = spannable.getSpans(0, ends, URLSpan.class);
    SpannableStringBuilder stylesBuilder = new SpannableStringBuilder(text);
    stylesBuilder.clearSpans(); // should clear old spans
    for (URLSpan url : urlspan) {
        TextViewURLSpan myURLSpan = new TextViewURLSpan(url.getURL());
        stylesBuilder.setSpan(myURLSpan, spannable.getSpanStart(url),
                spannable.getSpanEnd(url), spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    mTextView2.setText(stylesBuilder);

}

private class TextViewURLSpan extends ClickableSpan {
    private String clickString;

    public TextViewURLSpan(String clickString) {
        this.clickString = clickString;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        ds.setColor(TestActivity.this.getResources().getColor(R.color.read_mian));
        ds.setUnderlineText(false); //去掉下划线
    }

    @Override
    public void onClick(View widget) {
        if (clickString.equals("username")) {
            //点击不同文字你要跳转的页面
          } else if (clickString.equals("singstar")) {
            //点击不同文字你要跳转的页面
        }
    }
}

相关文章

网友评论

      本文标题:同一个TextView不同文字的点击事件

      本文链接:https://www.haomeiwen.com/subject/iotmyltx.html