我在尝试使用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
的行时,当我单击文本中的新位置时,光标不会更新。为什么是这样?