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.
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.
I think an InputFilter that rejects all changes is a good solution:
editText.setFilters(new InputFilter[] {
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
}
}
});
Edit: dlazar suggested (below) to change the return to dst.subSequence(dstart, dend) to overcome behavior that removes words.
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.
Have you tried setText(java.lang.CharSequence, android.widget.TextView.BufferType) ? It's described as:
Sets the text that this TextView is to display (see setText(CharSequence)) and also sets whether it is stored in a styleable/spannable buffer and whether it is editable.
(emphasis mine)
[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.
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);