EditText:使用自定义Editable调用setText()时,Cursor不会更新

时间:2017-07-07 23:48:36

标签: java android android-edittext android-editable

我在尝试使用实现Editable的自定义类型作为EditText的基础时遇到问题。这是我的代码:

// This is a custom type that implements Editable.
// It's just a wrapper over a SpannableStringBuilder, with some
// irrelevant added functionality.
public class ColoredText implements Editable {
    private final SpannableStringBuilder builder;

    public ColoredText(String text) {
        this.builder = new SpannableStringBuilder(text);
    }

    // All Editable methods are implemented through this.builder.
    @Override
    public Editable replace(int i, int i1, CharSequence charSequence, int i2, int i3) {
        this.builder.replace(i, i1, charSequence, i2, i3);
        return this;
    }

    ...
}

public class NoCopyEditableFactory extends Editable.Factory {
    @Override
    public Editable newEditable(CharSequence source) {
        return (Editable) source;
    }
}

// In MainActivity.java
@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    setContentView(R.layout.main);

    String line = "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE";
    String text = TextUtils.join("\n", Collections.nCopies(100, line));
    Editable e = new ColoredText(text);

    EditText et = (EditText) findViewById(R.id.editText);
    et.setEditableFactory(new NoCopyEditableFactory()); // This line is causing trouble.
    et.setText(e, TextView.BufferType.EDITABLE);
}

// In the MainActivity layout file
<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

出于某种原因,当我注释掉NoCopyEditableFactory时,光标会更新。但是,当我取消注释强制EditText不将ColoredText复制到新SpannableStringBuilder的行时,当我单击文本中的新位置时,光标不会更新。这是为什么?

1 个答案:

答案 0 :(得分:0)

问题原来是我的Editable实施。删除一些行为不当的代码后,它工作正常。