Spannable与Editable区别

在看TextView源码时候又看到了这两个接口:Spannable和Editable;android

以前一直没有认真研究过二者的关系,如今看了源码记录下来。网络

1:二者属于继承关系,Editable继承于Spannable

Editable: Editable继承关系.png Spannable: Spannable.pngapp

相较于Spannable,Editable还继承了另2个接口:CharSequence,Appendable。 CharSequence你们应该比较熟,看一下Appendable:ide

Appendable.png

由图可见,Appendable这个接口,主要用来向CharSequence 添加/插入新的文本,经过其定义的方法能够看出其做用:ui

  • append(CharSequence csq)
  • append(CharSequence csq, int start, int end)
  • append(char c)

2:Spannable中主要方法

  • setSpan(Object what, int start, int end, int flags)
    • 这个方法咱们常常用,用于向文本设置/添加新的样式
  • removeSpan(Object what)
    • 移除指定的样式,做用和setSpan相反

因而可知,Spannable做用是为CharSequence实例设置或者移除指定样式this

2:Editable中主要方法

Editable: Editable源代码.pngspa

This is the interface for text whose content and markup can be changed: 可见,Editable接口关联的文本,不只能够标记/设置样式,其内容也能够变化;code

3:实际使用总结

  • 若是一段文本,仅仅是样式发生变化,使用Spannable的子类SpannableString便可实现
  • 若是一段文本,样式和内容都要发生变化,则必须使用Editable实例,咱们最经常使用的应该就是SpannableStringBuilder.
  • 调用TextView实例的setText方法时,type使用TextView.BufferType.EDITABLE,能够实现TextView中的文本不断的增长/更新(好比一些场景是须要向TextView实例中不断插入从网络获取的最新数据
/**
     * Sets the text that this TextView is to display (see
     * {@link #setText(CharSequence)}) and also sets whether it is stored
     * in a styleable/spannable buffer and whether it is editable.
     *
     * @attr ref android.R.styleable#TextView_text
     * @attr ref android.R.styleable#TextView_bufferType
     */
    public void setText(CharSequence text, BufferType type) {
        setText(text, type, true, 0);

        if (mCharWrapper != null) {
            mCharWrapper.mChars = null;
        }
    }

示例代码:继承

.................    
        tv_setText = (TextView) findViewById(R.id.tv_setText);
        bt_setText = (Button) findViewById(R.id.bt_setText);
        tv_setText.setText("", TextView.BufferType.EDITABLE);
        bt_setText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Editable content = (Editable) tv_setText.getText();
                content.append(":"+(insertIndex++));
            }
        });
    }
    int insertIndex = 0;

That's all !接口

相关文章
相关标签/搜索