Android 如何在editText中启用覆盖模式
在Android应用程序中,我需要让用户在插入/覆盖模式之间进行选择,就像普通PC上的“插入”键一样。我使用editText组件。有没有简单的方法可以做到这一点,通过设置一些属性,调用一些方法(我还没有找到)?在这种情况下,我是否应该使用其他组件作为文本编辑器?尝试此自定义TextWatcher:Android 如何在editText中启用覆盖模式,android,user-interface,Android,User Interface,在Android应用程序中,我需要让用户在插入/覆盖模式之间进行选择,就像普通PC上的“插入”键一样。我使用editText组件。有没有简单的方法可以做到这一点,通过设置一些属性,调用一些方法(我还没有找到)?在这种情况下,我是否应该使用其他组件作为文本编辑器?尝试此自定义TextWatcher: LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); fina
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);
非常感谢。它可以工作,但在Logcat中给出了错误:
03-12 15:13:22.438:E/SpannableStringBuilder(2442):SPAN_EXCLUSIVE\u EXCLUSIVE SPAN不能有零长度
我应该注意这个错误吗?我不知道。这是用logcat写的。在Android API和适当的对象组中有这样一个术语“Span”,“Spannable”,但我不知道那是什么。好啊看来我应该探究一下。非常感谢。不幸的是,我的排名太低了,不能给你的答案打分。对不起,亲爱的!当我在“Go键盘”上切换当前语言时,会出现这些错误。它们与您的代码无关。再次感谢你,为我的错误感到抱歉!你帮了大忙!