Android 中SpannableStringBuilder控制局部文本颜色和点击事件

直接上代码


package com.lhl.qsmm.maskguidetest;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.text);
        SpannableStringBuilder builder = new SpannableStringBuilder();
        String s1 = "你好";
        SpannableString sp1 = new SpannableString(s1);
        sp1.setSpan(new Clickable(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //在这里添加点击事件
            }
        }),0,s1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan fcs1 = new ForegroundColorSpan(ContextCompat.getColor(this,R.color.borline));
        sp1.setSpan(fcs1,0,s1.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//设置字体的颜色
        builder.append(sp1);//添加

        String s2 = "安卓";
        SpannableString sp2 = new SpannableString(s2);
        sp2.setSpan(new Clickable(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //在这里添加点击事件
                Toast.makeText(MainActivity.this, "点击", Toast.LENGTH_SHORT).show();
            }
        }),0,s2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan fcs2 = new ForegroundColorSpan(ContextCompat.getColor(this,R.color.brightred));
        sp1.setSpan(fcs2,0,s1.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//设置字体的颜色
        builder.append(sp2);
        mTextView.setText(builder);
        mTextView.setMovementMethod(LinkMovementMethod.getInstance());//加上这句话才有效果

        mTextView.setHighlightColor(ContextCompat.getColor(this,R.color.touming));//去掉点击后的背景颜色为透明
    }

    class Clickable extends ClickableSpan implements View.OnClickListener {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener mListener) {
            this.mListener = mListener;
        }

        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);    //去除超链接的下划线
        }
    }
}
结果
Android 中SpannableStringBuilder控制局部文本颜色和点击事件_第1张图片

你可能感兴趣的:(Android)