Make EditText ReadOnly

前端 未结 22 1312

I want to make a read-only EditText view. The XML to do this code seems to be android:editable=\"false\", but I want to do this in code.

H

22条回答
  •  旧时难觅i
    2020-12-04 19:16

    this is my implementation (a little long, but useful to me!): With this code you can make EditView Read-only or Normal. even in read-only state, the text can be copied by user. you can change the backgroud to make it look different from a normal EditText.

    public static TextWatcher setReadOnly(final EditText edt, final boolean readOnlyState, TextWatcher remove) {
        edt.setCursorVisible(!readOnlyState);
        TextWatcher tw = null;
        final String text = edt.getText().toString();
        if (readOnlyState) {
                tw = new TextWatcher();
    
                @Override
                public void afterTextChanged(Editable s) {
    
                }
                @Override
                //saving the text before change
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }
    
                @Override
                // and replace it with content if it is about to change
                public void onTextChanged(CharSequence s, int start,int before, int count) {
                    edt.removeTextChangedListener(this);
                    edt.setText(text);
                    edt.addTextChangedListener(this);
                }
            };
            edt.addTextChangedListener(tw);
            return tw;
        } else {
            edt.removeTextChangedListener(remove);
            return remove;
        }
    }
    

    the benefit of this code is that, the EditText is displayed as normal EditText but the content is not changeable. The return value should be kept as a variable to one be able revert back from read-only state to normal.

    to make an EditText read-only, just put it as:

    TextWatcher tw = setReadOnly(editText, true, null);
    

    and to make it normal use tw from previous statement:

    setReadOnly(editText, false, tw);
    

提交回复
热议问题