In an Android application I need to let the user choose between insert/overwrite modes just like "Insert" key does on ordinary PC. I use editText component. Is there any easy way to do that, by setting some attribute, calling some method(i haven't found one)? Should i use some other component as text editor in this case?
Asked
Active
Viewed 2,012 times
1 Answers
2
try this custom 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);

pskink
- 23,874
- 6
- 66
- 77
-
Thank You! It works, but gives errors in Logcat: `03-12 15:13:22.438: E/SpannableStringBuilder(2442): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length` Should i pay attention to this error? – Roman Mar 12 '14 at 11:15
-
I don't know. This was written in logcat. There is such a term "Span", "Spannable" in Android API and appropriate group of objects, but i don't know what is that. OK. Looks like i should explore this. Thank You. Unfortunately my rank is too low to rate Your answer. – Roman Mar 13 '14 at 14:27
-
I'm sorry pskink! Those errors appear when I switch current language on "Go Keyboard". They have nothing to do with Your code. Thank You again and sorry for my mistake! You helped greatly! – Roman Mar 17 '14 at 15:16