SpannableString的简单用法


 按照我的理解SpannableString     举个例子:就是让我们做出向一些登录授权中,那几行字上有的会有下划线,或者点击文字,跳转网页,还有我们使用的QQ中发消息的时候,文字加表情,实现图文混排的效果等等。。。



public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView name = (TextView) findViewById(R.id.name);
        //封装一个SpannableString
        SpannableString spannableString = new SpannableString("热烈庆祝十九大顺利召开,跟着党走是我的信念");
        //背景色
        spannableString.setSpan(new BackgroundColorSpan(Color.RED),2,5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //前景色
        spannableString.setSpan(new ForegroundColorSpan(Color.BLUE),2,5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //下划线
        spannableString.setSpan(new UnderlineSpan(),0,5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        //图片(图文混排)
        Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
        drawable.setBounds(0,0,80,80);
        spannableString.setSpan(new ImageSpan(drawable),5,6, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //加粗
        spannableString.setSpan(new StyleSpan(Typeface.BOLD_ITALIC),7,9, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //下标
        spannableString.setSpan(new SubscriptSpan(),7,9, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        //超文本链接
        spannableString.setSpan(new URLSpan("http://www.baidu.com"),10,12, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        //点击事件
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                System.out.println("widget"+widget);
            }
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                //可以改变颜色
                ds.setColor(Color.RED);
                ds.setUnderlineText(true);
            }
        },13,15,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);



        name.setText(spannableString);
        //超文本需要加的代码
        name.setMovementMethod(new LinkMovementMethod());



        //输入框中
        EditText et_name = (EditText) findViewById(R.id.et_name);
        SpannableString spannableString1 = new SpannableString("跟着党走是我的信念");
        spannableString1.setSpan(new ForegroundColorSpan(Color.BLUE),0,4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        et_name.setText(spannableString1);
    }
}



  下面可以参考:


SpannableString的简单用法_第1张图片SpannableString的简单用法_第2张图片SpannableString的简单用法_第3张图片SpannableString的简单用法_第4张图片SpannableString的简单用法_第5张图片SpannableString的简单用法_第6张图片






你可能感兴趣的:(android-studio)