Disabling of EditText in Android

2020-01-25 03:43发布

In my application, I have an EditText that the user only has Read access not Write access.

In code I set android:enabled="false".

Although the background of EditText changed to dark, when I click on it the keyboard pops up and I can change the text.

What should I set to disable EditText?

23条回答
▲ chillily
2楼-- · 2020-01-25 04:19

Today I still use editable="false", but also with focusable="false".

I think the case we need to make an EditText un-editable, is because we want to keep its EditText style (with that underline, with hint, etc), but it accepts other inputs instead of text. For example a dropdown list.

In such use case, we need to have the EditText clickable (thus enabled="false" is not suitable). Setting focusable="false" do this trick, however, I can still long hold on the EditText and paste my own text onto it from clipboard. Depending on your code and handling this can even crash your app.

So I also used editable="false" and now everything is great, except the warning.

查看更多
Summer. ? 凉城
3楼-- · 2020-01-25 04:19

you can use android:focusable="false" but also need to disable cursor otherwise copy/paste function would still work.

so, use

android:focusable="false"
android:cursorVisible="false"
查看更多
萌系小妹纸
4楼-- · 2020-01-25 04:24

You can try the following method :

 private void disableEditText(EditText editText) {
    editText.setFocusable(false);
    editText.setEnabled(false);
    editText.setCursorVisible(false);
    editText.setKeyListener(null);
    editText.setBackgroundColor(Color.TRANSPARENT); 
 }

Enabled EditText :

Enabled EditText

Disabled EditText :

Disabled EditText

It works for me and hope it helps you.

查看更多
Rolldiameter
5楼-- · 2020-01-25 04:24

Set this in your XML code, It works.

android:focusableInTouchMode="false"

查看更多
对你真心纯属浪费
6楼-- · 2020-01-25 04:26
android:editable="false"

is now deprecated and use

 YourEditText.setInputType(InputType.TYPE_NULL);
查看更多
Emotional °昔
7楼-- · 2020-01-25 04:28

if you use android:editable="false", eclipse will remind you this message "android:editable is deprecated: Use inputType instead".

So, I use android:focusable="false" instead, it worked well for me.

查看更多
登录 后发表回答