Android - EditText not editable and not selectable

2019-07-14 02:20发布

问题:

In my activity code I have these lines

EditText editText=(EditText)findViewById(R.id.editText);
editText.setTextIsSelectable(false);

What I want to achieve is a EditText uneditable and unselectable. With the previous line I try to achieve the second option, but it'doesn't work. The EditText is still selectable.

In order to make the EditText uneditable I have not found any method such as setEditable or similar. I read about setting InputType but I had no success.

However the unselectable constraint can be weakened. My main goal is that the text inside the EditText cannot change for any reason. For these reason the EditRext could be selectable but I want that no user can cut the text.

I want no XML but only Java code. All these things are needed to to programmatically.

回答1:

Sorry guys, at least for my setup (Sdk Version 25 with AppCompatActivity)

editText.setFocusable(false);

will still let me push the return button of the virtual keyboard, adding lines to the text. If you add

editText.setEnabled(false);

this behaviour stopps, however, the text is greyed out.

Therefore, I think the following would be a better solution:

editText.setInputType(0);


回答2:

This works fine; just set focusable property of your edittext to "false" and you are done.

<EditText
        android:id="@+id/EditTextInput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:gravity="right"
        android:cursorVisible="true">
    </EditText>


回答3:

I would implement the following code:

editText.setFocusable(false);
editText.setClickable(false);
editText.setEnabled(false);

Which should prevent interacting with the EditText. Read more about the View class here since EditText extends from it:

https://developer.android.com/reference/android/view/View.html#setFocusable(boolean)