Android - EditText not editable and not selectable

2019-07-14 02:04发布

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.

3条回答
一夜七次
2楼-- · 2019-07-14 02:09

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)

查看更多
冷血范
3楼-- · 2019-07-14 02:12

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);
查看更多
虎瘦雄心在
4楼-- · 2019-07-14 02:23

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>
查看更多
登录 后发表回答