本文翻译自:How to make EditText not editable through XML in Android?
Can anyone tell me how to make an EditText
not editable via XML? 谁能告诉我如何使EditText
不能通过XML编辑? I tried setting android:editable
to false
, but 我尝试将android:editable
设置为false
,但是
- it is deprecated; 它已被弃用; and 和
- it didn't work. 它不起作用。
#1楼
参考:https://stackoom.com/question/gu2j/如何在Android中通过XML编辑EditText
#2楼
<EditText
android:id="@+id/txtDate"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="2dp"
android:clickable="false"
android:cursorVisible="false"
android:gravity="center" />
and use following : 并使用以下:
txtDate.setKeyListener(null);
#3楼
Try this code. 试试这个代码。 It's working in my project, so it will work in your project. 它在我的项目中工作,因此它将在您的项目中工作。
android:editable="false"
#4楼
As you mentioned android:editable is deprecated. 正如你提到的android:editable已被弃用。 android:inputType="none" should be used instead but it does not work due to a bug ( https://code.google.com/p/android/issues/detail?id=2854 ) 应该使用android:inputType =“none”但由于错误而无效( https://code.google.com/p/android/issues/detail?id=2854 )
But you can achieve the same thing by using focusable. 但是你可以通过使用可聚焦来实现同样的目的。
Via XML: 通过XML:
<EditText ...
android:focusable="false"
</EditText>
From code: 来自代码:
((EditText) findViewById(R.id.LoginNameEditText)).setFocusable(false);
#5楼
In addition to @mahe madi you can try this as well 除了@mahe madi,你也可以尝试这个
editText.setEnabled(false);
editor.setTextColor(Color.BLACK);
This method will hide cursor, lose focus and more importantly set text color to black behaving like TextView. 此方法将隐藏光标,失去焦点,更重要的是将文本颜色设置为黑色,表现得像TextView。
And to revert Back to editText simply do this to gain all the properties of EditText. 要恢复返回editText,只需执行此操作即可获得EditText的所有属性。
editText.setEnabled(true);
Hope it Helps :) 希望能帮助到你 :)
#6楼
You could use android:editable="false"
but I would really advise you to use setEnabled(false)
as it provides a visual clue to the user that the control cannot be edited. 您可以使用android:editable="false"
但我建议您使用setEnabled(false)
因为它为用户提供了无法编辑控件的直观线索。 The same visual cue is used by all disabled widgets and consistency is good. 所有禁用的小部件都使用相同的视觉提示,并且一致性良好。