Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable overwrite mode in editText

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?

like image 569
Roman Avatar asked Mar 16 '26 11:03

Roman


1 Answers

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);
like image 158
pskink Avatar answered Mar 18 '26 00:03

pskink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!