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条回答
爷的心禁止访问
2楼-- · 2020-01-24 22:02
android:editable="false" 
android:inputType="none" 

in your xml or

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

or

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
查看更多
闹够了就滚
3楼-- · 2020-01-24 22:04

[Posting a new answer, since I can't comment on Josef's answer.]

The input filter works fine, but it has a subtle bug in it: typing over a selection will delete all the text.

For example, say you have the text "foo" in the EditText. If you select it all (e.g., by double-clicking on it) and type 'a', the text will disappear. This is because the InputFilter will be called as:

filter("a", 0, 1, "foo", 0, 3);

The proposed input filter will return the empty string in this case (because src.length() < 1 is false), which explains the missing text.

The solution is to simply return dst.subSequence(dstart, dend) in the filter function. This will work fine even for deletions.

查看更多
登录 后发表回答