谁能告诉我如何使一个EditText不可编辑通过XML?我试着设置android:editable为false,但是

已弃用;而且 但是没有成功。


当前回答

Kotlin扩展选项:

fun AppCompatAutoCompleteTextView.setEditable(editable: Boolean) {
    if (!editable) {
        this.tag = this.keyListener
        this.keyListener = null
    } else {
        if(this.tag is KeyListener) {
            this@setEditable.keyListener = this@setEditable.tag as KeyListener
        }
    }
}

其他回答

除了@mahe madi 你也可以试试这个

editText.setEnabled(false);
editor.setTextColor(Color.BLACK);

这个方法将隐藏光标,失去焦点,更重要的是设置文本颜色为黑色,就像TextView一样。

要恢复回editText,只需这样做即可获得editText的所有属性。

editText.setEnabled(true);

希望能有所帮助。

<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" />

并使用以下:

txtDate.setKeyListener(null);

这个组合对我很有效:

<EditText ... >
    android:longClickable="false"
    android:cursorVisible="false"
    android:focusableInTouchMode="false"
</EditText>

我也遇到过同样的问题,但经过观察,我发现android:editable="false"只有当inputtype (android: inputtype ="ANY_VALUE")没有在Edittext中给出时才会工作。

从EditText中删除inputType并使用editable = false,其工作正常。

正如你提到的,android:editable已被弃用。android:inputType="none"应该被用来代替,但它不工作,由于一个bug (https://code.google.com/p/android/issues/detail?id=2854)

但是你可以通过使用focusable来达到同样的效果。

通过XML:

<EditText ...
        android:focusable="false" 
</EditText>

从代码:

((EditText) findViewById(R.id.LoginNameEditText)).setFocusable(false);