如何在显示消息后取消EditText的文本更改?

时间:2018-05-15 05:11:35

标签: android android-edittext

我可以停用EditText,但用户根本无法更改文字。我试图实现的行为是,如果用户尝试键入某些内容(或任何其他更改方法,如粘贴),则显示类似&#34的消息;由于某些原因,您无法编辑此文本。"。

起初,我以为我可以使用TextWatcher显示消息,但似乎无法取消更改。我怎样才能实现我正在寻找的行为?我能想到的唯一方法是以下非常脏的方式。

  

备份EditText的文本。当EditText更改时,   如果isReverting为false,请显示该消息并将isReverting设置为   真正。如果isReverting为真,则将其设置为false。设置备份   到EditText。

4 个答案:

答案 0 :(得分:0)

<EditText
        android:id="@+id/amount"
        android:inputType="number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:editable="false"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="4dp" />

答案 1 :(得分:0)

您的解决方案非常有效。您也可以将不可修改的值存储在变量中,如果值不同,只需在afterTextChanged中更改文本。

答案 2 :(得分:0)

您可以通过以编程方式使用以下属性来使EditText不可编辑

editText.setEnabled(false);

不需要textChangeListner

答案 3 :(得分:0)

TextWatcher将满足您的需求。在afterTextChange()内进行验证。以下是一个例子。

et_Name.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            String input=s.toString();
            if(s.length()>4){
                Toast.makeText(MainActivity.this, "You can only input 4 letters",
                        Toast.LENGTH_SHORT).show();
                String old=input.substring(0,4);
                et_Name.setText(old);
                et_Name.setSelection(old.length());
            }
        }
    });