zoukankan      html  css  js  c++  java
  • android-tip-关于SpannableString的使用

    如果想单独设置TextView上其中几个字的样式,该怎么办?
    答案是使用SpannableString。
    使用SpannableString可以为TextView上的某字或某些字设置:
    前景色(ForegroundColorSpan)
    背景色(BackgroundColorSpan)、
    设置字体(TypefaceSpan)、
    点击事件(ClickableSpan)、
    设置掩码(MaskFilterSpan)、
    删除线效果(StrikethroughSpan)、
    下划线效果(UnderlineSpan)、
    插入图片(ImageSpan)等
    想要实现自定义的样式,查看这个文档:
    1. 简单示例
    设置文字的前景色

     1 SpannableString name = new SpannableString("abc");

    2 ForegroundColorSpan nameSpan = new ForegroundColorSpan(Color.BLUE);
    3 name.setSpan(nameSpan, 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    4 textView.setText(name);
    2. 使用SpannableStringBuilder构造复杂的样式
    例如,我们写一个聊天程序,需要将用户名设置成绿色,将聊天内容设置成红色,可以这么干:
     1 SpannableStringBuilder spanBuilder = new SpannableStringBuilder();
     2 // name
     3 SpannableString name = new SpannableString("name");
     4 ForegroundColorSpan nameSpan = new ForegroundColorSpan(Color.BLUE);
     5 name.setSpan(nameSpan, 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
     6 spanBuilder.append(name);
     7 
     8 // msg
     9 SpannableString msg = new SpannableString("msg");
    10 ForegroundColorSpan msgSpan = new ForegroundColorSpan(Color.RED);
    11 msg.setSpan(msgSpan, 0, msg.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    12 spanBuilder.append(msg);
    13 

    14 textView.setText(spanBuilder); 

    3. 插入图片
    1 // image
    2 SpannableString image = new SpannableString("image");
    3 ImageSpan imageSpan = new ImageSpan(ctx, imageResourceId, DynamicDrawableSpan.ALIGN_BASELINE);
    4 image.setSpan(imageSpan, 0, image.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    5 
    6 textView.setText(image);
    4. 为文字设置点击事件
    如果我们需要问某个字或某几个字设置点击事件,可以这么干:
     1 // name
     2 ClickableSpan clickSpan = new ClickableSpan() {
     3 
     4 @Override
     5  public void onClick(View widget) {
     6     Toast.makeText(context, "clickspan",  Toast.LENGTH_LONG).show();
     7  }
     8  @Override
     9  public void updateDrawState(TextPaint ds) {
    10    super.updateDrawState(ds);
    11    // 去掉下划线
    12    ds.setUnderlineText(false);
    13 
    14    // 设置文字颜色
    15    ds.setColor(Color.BLUE);
    16  }
    17 };
    18 
    19 SpannableString name = new SpannableString(cmd.srcName() + ":");
    20 name.setSpan(clickSpan, 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    21 

    22 textView.setText(name); 

    注意默认状态下,TextView不会响应点击事件,还需要这么设置一下:
    1 txtView.setMovementMethod(LinkMovementMethod.getInstance());
  • 相关阅读:
    MySQL数据库返回影响行数的实际操作流程
    nslookup命令
    Mysql Strict Mode
    mysql表大小写
    Objective-C消息转发
    NSDateFormatter 和 NSDateComponents 的用法
    提交app的时候总是报出icon的错误
    IOS 的loadView 及使用loadView中初始化View注意的问题。(死循环并不可怕)
    [[NSMutableArray alloc] init];和[[NSMutableArray alloc] initWithCapacity:0]区别
    NSMutableArray初始化崩溃问题
  • 原文地址:https://www.cnblogs.com/hdtianfu/p/5223915.html
Copyright © 2011-2022 走看看