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

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


当前回答

我试着这样做:

textView.setInputType( InputType.TYPE_NULL );

这应该有用,但对我来说没用。

我完成了下面的代码:

textView.setKeyListener(new NumberKeyListener() {
    public int getInputType() {
        return InputType.TYPE_NULL;
    }

    protected char[] getAcceptedChars() {
        return new char[] {};
    }
});

这很完美。

其他回答

你可以使用android:editable="false",但我真的会建议你 使用setEnabled(false),因为它为用户提供了一个视觉线索 控件不能编辑。所有人都使用相同的视觉线索 禁用小部件和一致性很好。

disable from XML(一行):

 android:focusable="false"

从Java重新启用,如果需要(也是一行):

editText.setFocusableInTouchMode(true);

只需使用android:enabled="false"即可。这也会给EditText一个外观,使它看起来不可编辑。

使用这段简单的代码:

textView.setKeyListener(null);

它的工作原理。

编辑:如果稍后要添加KeyListener,请执行以下操作

1:设置关键监听器为textView的标签

textView.setTag(textView.getKeyListener());
textView.setKeyListener(null);

2:从标签中获取关键监听器,并将其设置回textView

textView.setKeyListener((KeyListener) textView.getTag());
<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);