EditText设置可以编辑和不可编辑状态

1、首先想到在xml中设置android:editable="false",但是如果想在代码中动态设置可编辑状态,没有找到对应的函数

2、然后尝试使用editText.setFocusable(false);和editText.setEnabled(false);设置不可编辑状态;editText.setFocusable(true);和 editText.setEnabled(true);设置可编辑状态。

发现在editText.setFocusable(false);和editText.setEnabled(false);时不可编辑,但是editText.setFocusable(true);和 editText.setEnabled(true);也是不可编辑的,感觉这个时候EditText控件高亮度了,但是没有焦点

3、最后尝试使用editText.setFocusable(false);和editText.setFocusableInTouchMode(false);设置不可编辑状态;editText.setFocusableInTouchMode(true);editText.setFocusable(true);editText.requestFocus();设置可编辑状态

这个可以实现可编辑和不可编辑,但是又发现一个问题,在不可编辑状态如果常按住控件,可以进行粘帖操作,不知道怎么可以不能进行粘帖啊

--------------------------------------------------------

其实可以直接通过setEnable(true)编辑;setEnable(false)编辑

----------------------------------------------------------

android:editable is deprecated: Use an <EditText> to make it editable
android:editable is deprecated: Use inputType instead

分析:关于EditText控件的read-only问题,即: 无法通过UI更改其中的内容, 但可以选定部分内容, 进行复制.在早期的sdk, EditText有Editable属性, 现在这个属性已经deprecated了.
 
解决方法:
其实只需一行代码就能搞定et.setKeyListener(null);
注意, 这里不是setOnKeyListener, 而是setKeyListener. 此方法是TextView的成员, 调用后的效果完全符合预期, 并且获得焦点后不会弹出输入法. 
 
下面是官方文档的解释

Sets the key listener to be used with this TextView. This can be null to disallow user input. Note that this method has significant and subtle interactions with soft keyboards and other input method: see KeyListener.getContentType() for important details. Calling this method will replace the current content type of the text view with the content type returned by the key listener.
 
Be warned that if you want a TextView with a key listener or movement method not to be focusable, or if you want a TextView without a key listener or movement method to be focusable, you must call setFocusable again after calling this to get the focusability back the way you want it.

原文地址:https://www.cnblogs.com/exmyth/p/4667462.html