How to replicate android:editable=“false” in code?

2020-01-24 21:19发布

In the layout you can set the EditText widget to be non-editable via the android:editable attribute.

How can I do this in code? I need to make the EditText widget to be editable depending on conditions.

14条回答
Fickle 薄情
2楼-- · 2020-01-24 21:39

The best way to do this is with this single line of code:

textView.setKeyListener(null);

The docs say for this method:

Sets the key listener to be used with this TextView. This can be null to disallow user input.

查看更多
神经病院院长
3楼-- · 2020-01-24 21:40

I guess

Edittext.setEnabled(false); 

through code

and

android:enabled="false"

through xml.Also check this post on SO.

They should work and you can enable again programatically Edittext.setEnabled(true);

查看更多
我想做一个坏孩纸
4楼-- · 2020-01-24 21:44

I wanted to also point out an alternative solution that works nicely if you are creating new instances of an EditView. You can override the method getDefaultEditable() as suggested by the docs to return false. E.g.

EditText view = new EditText(DiscountCalculator.this) {
    public boolean getDefaultEditable() {
        return false;
    }
};
查看更多
何必那么认真
5楼-- · 2020-01-24 21:45

I think the correct way to achieve the desired effect is:

mEditView.setText("my text", BufferType.NORMAL);

If you want to switch between editable and non-editable you can do the following:

// Switch to non-editable
mEditView.setText(mEditView.getText(), BufferType.NORMAL);

// Switch back to editable
mEditView.setText(mEditView.getText(), BufferType.EDITABLE);
查看更多
Juvenile、少年°
6楼-- · 2020-01-24 21:45

try this:

 mEditText.setFilters(new InputFilter[]{new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (XXX) {
                return "";
            } else {
                return null;
            }
        }
    }});
查看更多
混吃等死
7楼-- · 2020-01-24 21:46

I do not see a related method for that attribute in the EditText class. However, there are other similar things you could use such as android:focus/setFocusable(boolean) or create another TextView whose android:editable="false" and use setVisiblilty() to switch between the editable and not editable views. If you use View.GONE the user will never know there are two EditTexts.

If your feeling ambitious you could probably do something with the EditText's onTextChanged listener like having it react with a setText.

查看更多
登录 后发表回答