views:

2238

answers:

4

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.

+2  A: 

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.

Will
+2  A: 

Have you tried http://developer.android.com/reference/android/widget/EditText.html#setText%28java.lang.CharSequence,%20android.widget.TextView.BufferType%29/">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)

pjz
Thanks for the effort, but I just tried and it makes no difference whatsoever. Furthermore, there isn't any documentation on what the enum values even mean.
AngryHacker
+2  A: 

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) : "";
     }
    }
});
Josef
+1  A: 

[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.

dlazar