在Android应用程序中,我需要让用户在插入/覆盖模式之间进行选择,就像普通PC上的“插入”键一样。我使用editText组件。有没有简单的方法,通过设置一些属性,调用一些方法(我还没有找到一个)?在这种情况下,我应该使用其他组件作为文本编辑器吗?
答案 0 :(得分:2)
试试这个自定义TextWatcher:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final ToggleButton tb = new ToggleButton(this);
tb.setTextOff("insert");
tb.setTextOn("overwrite");
tb.setTextSize(20);
tb.setChecked(false);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(tb, params);
EditText et = new EditText(this);
et.setTextSize(20);
params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
ll.addView(et, params);
setContentView(ll);
TextWatcher watcher = new TextWatcher() {
boolean formatting;
int mStart;
int mEnd;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
this.mStart = -1;
if (tb.isChecked() && before == 0) {
mStart = start + count;
mEnd = Math.min(mStart + count, s.length());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (!formatting) {
if (mStart >= 0) {
formatting = true;
// Log.d(TAG, "afterTextChanged s " + start);
// Log.d(TAG, "afterTextChanged e " + end);
s.replace(mStart, mEnd, "");
formatting = false;
}
}
}
};
et.addTextChangedListener(watcher);