Android TextView实现富文本

2019-07-11  本文已影响0人  土人徐

TextView支持字号放大改变颜色添加链接等等富文本操作

示例:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView mTextView = (TextView) findViewById(R.id.text);
        //将TextView的显示文字设置为SpannableString
        mTextView.setText(getClickableSpan());
        //设置该句使文本的超连接起作用
        mTextView.setMovementMethod(LinkMovementMethod.getInstance());
    }

    //设置超链接文字
    private SpannableString getClickableSpan() {
        SpannableString spanStr = new SpannableString("感谢您使用错题本,当您使用我们的软件时,我们会基于产品服务场景的需求,收集和使用您的部分个人信息。请您仔细阅读《错题本隐私政策》和《用户协议》了解并确定我们对您个人信息的处理原则");
        //设置文字的单击事件
        spanStr.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                startActivity(new Intent(MainActivity.this, PrivacyActivity.class));
            }
        }, 55, 64, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置文字的前景色
        spanStr.setSpan(new ForegroundColorSpan(Color.RED), 55, 64, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置下划线文字
        spanStr.setSpan(new UnderlineSpan(), 55, 64, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置文字的单击事件
        spanStr.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                startActivity(new Intent(MainActivity.this, AgreementActivity.class));
            }
        }, 65, 71, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置文字的前景色
        spanStr.setSpan(new ForegroundColorSpan(Color.BLUE),65, 71, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanStr;
    }

更多支持的富文本标签请查看:android.jar下的android.text.style package下的Span类。
另外注意有超链接需要设置mTextView.setMovementMethod(LinkMovementMethod.getInstance());
上一篇 下一篇

猜你喜欢

热点阅读