Android SpannableString

SpannableString

  • ForegroundColorSpan(设置字体前景色,字体颜色)
  • UnderlineSpan(设置下划线)
  • ClickableSpan (设置点击事件)
  • RelativeSizeSpan(设置文字相对大小,,相对设置文字大小)
  • ClickableSpan( 文字的点击事件)

效果图片

Android SpannableString_第1张图片
1.jpg

public class MainActivity extends AppCompatActivity {

    public String content="服务端获取到之后会去数据库中查询其对应的本次需要升级的apk包以及旧版本号对应的旧apk包,然后进行差分处理得到差分文件,在下发到客户端即可。";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          SpannableString spannableString=new SpannableString(content);

          TextView tv_content= (TextView) findViewById(R.id.tv_content);
          TextView tv_content1= (TextView) findViewById(R.id.tv_content1);
          TextView tv_content2= (TextView) findViewById(R.id.tv_content2);

          tv_content.setText(spannableString);

        final int startIndex=1;
         final int endIndex=20;
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#113EAA")), startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new UnderlineSpan(),startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new RelativeSizeSpan(1.2f),startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        StrikethroughSpan strikethroughSpan= new StrikethroughSpan();
        spannableString.setSpan(strikethroughSpan,startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tv_content1.setText(spannableString);

        int leftIndex=10;

        // 下滑线
        spannableString.setSpan(new UnderlineSpan(){

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#113EAA"));
                ds.setUnderlineText(true);
            }
        }, startIndex, leftIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 下滑线
        spannableString.setSpan(new UnderlineSpan(){

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#FF004F"));
                ds.setUnderlineText(true);
            }
        }, leftIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 点击事件
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Toast.makeText(MainActivity.this,"点击了 "+content.substring(startIndex,endIndex).toString(),1).show();

            }
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
            }
        }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        tv_content2.setText(spannableString);
        // 一定要加 不然点击效果没有用
        tv_content2.setMovementMethod(LinkMovementMethod.getInstance());
    }
}


你可能感兴趣的:(Android SpannableString)