Android 如果 EditText 为空,如何禁用按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22680106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:19:54  来源:igfitidea点击:

How to disable Button if EditText is empty ?

androidbutton

提问by Nevaeh

I have an EditText and a Button in my application.

我的应用程序中有一个 EditText 和一个 Button。

When the button is clicked,the text entered in the EditText is added to a ListView.

单击按钮时,在 EditText 中输入的文本将添加到 ListView。

I want to disable the Button if the EditText is empty.How to do this ?

如果 EditText 为空,我想禁用按钮。如何执行此操作?

This is my code for button click

这是我的按钮点击代码

ImageButton imb=(ImageButton)findViewById(R.id.btn_send);
            imb.setOnClickListener(new OnClickListener()
            {
             @Override
             public void onClick(View arg0) 
             { 
                 EditText et = (EditText)findViewById(R.id.EditText1);

                  String str = et.getText().toString();
                  web1.add(str);
                  Toast.makeText(ShoutSingleProgram.this, "You entered...."+str, Toast.LENGTH_SHORT).show();
                  adapter1.notifyDataSetChanged();
                  et.setText("");

                    }
            });
            }

How can i do this ?

我怎样才能做到这一点 ?

回答by drulabs

    editText1.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

           if(s.toString().trim().length()==0){
                button.setEnabled(false);
              } else {
                button.setEnabled(true);
              }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

回答by Chirag Ghori

Use TextChangedListenerand initially disable ImageButtonin onCreate().

在 onCreate() 中使用TextChangedListener和最初禁用ImageButton

Try this

尝试这个

public class MyActivity extends Activity {

ImageButton imb;
EditText et;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imb = (ImageButton) findViewById(R.id.btn_send);
    et = (EditText) findViewById(R.id.EditText1);

    imb.setEnabled(false); // set button disable initially

    et.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

            if (s.toString().equals("")) {
                imb.setEnabled(false);
            } else {
                imb.setEnabled(true);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

}

}

回答by InnocentKiller

Simple just check the condition in onCreate

简单只需检查 onCreate 中的条件

if (et.getText().toString().trim().equals("")){
  button.setEnabled(false);
}
else{
button.setEnabled(true);
}

回答by mharper

I used TextUtilsfor a concise solution:

我使用TextUtils了一个简洁的解决方案:

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            button.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

回答by Khemraj

Easy Solution

简单的解决方案

This is very easy to implement in Data-Binding. I hope you are aware of it at this time. You can manage Button with EditText via only XML.

这在Data-Binding 中很容易实现。我希望你在这个时候意识到这一点。您可以仅通过 XML 使用 EditText 管理 Button。

android:enabled="@{etName.text.length() > 0 && etPassword.text.length() > 5}"

Which is equivalent to

这相当于

button.setEnabled(etName.getText().length() > 0 && etPassword.getText().length() > 5 );
  • Here &is HTML entitywhich denotes to &. There can be any operator like &.

  • etName& etPasswordare EditTexts ids.

  • &是表示 to 的HTML 实体&。可以有像 & 这样的任何运算符。

  • etName&etPassword是 EditTexts id。

Complete XML -

完整的 XML -

<LinearLayout
    >

    <EditText
        android:id="@+id/etName"
        />

    <EditText
        android:id="@+id/etPassword"
        />

    <Button
        android:enabled="@{etName.text.length() > 5 &amp;&amp; etPassword.text.length() > 5}"
        />

</LinearLayout>

回答by Stevo

Here's a super simple answer in Kotlin.

这是 Kotlin 中的一个超级简单的答案。

Just replace 'EditText' and 'Button' with your own.

只需用您自己的替换“EditText”和“Button”即可。

Button.isEnabled = false
        EditText.addTextChangedListener(object: TextWatcher {
            override fun onTextChanged(s:CharSequence, start:Int, before:Int, count:Int) {
                Button.isEnabled = s.toString().trim{ it <= ' ' }.isNotEmpty()
            }
            override fun beforeTextChanged(s:CharSequence, start:Int, count:Int,
                                           after:Int) {
            }
            override fun afterTextChanged(s: Editable) {
            }
        })

For Multiple EditTexts go

对于多个 EditTexts 去

Button.isEnabled = false
            val editTexts = listOf(editText1, editText2, editText3, editText4, editText5, editText6)
for (editText in editTexts) {
            editText.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                var et1 = editText1.text.toString().trim()
                var et2 = editText2.text.toString().trim()
                var et3 = editText3.text.toString().trim()
                var et4 = editText4.text.toString().trim()
                var et5 = editText5.text.toString().trim()
                var et6 = editText6.text.toString().trim()

                computeBtn.isEnabled = et1.isNotEmpty()
                        && et2.isNotEmpty()
                        && et3.isNotEmpty()
                        && et4.isNotEmpty()
                        && et5.isNotEmpty()
                        && et6.isNotEmpty()
            }

            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun afterTextChanged(
                s: Editable) {
            }
        })
        }

回答by agamov

Add a TextWatcher to your EditText, so that when you change the text inside it, you Button enables or disables itself.

将 TextWatcher 添加到您的 EditText,以便当您更改其中的文本时,您 Button 会启用或禁用自身。

回答by agamov

Initally in onCreate()disable the button. Then add a addTextChangedListenerto the edit text. within that check the edittext length and disable if it is 0 or otherwise enable it

最初在onCreate()禁用按钮。然后addTextChangedListener在编辑文本中添加一个。在其中检查edittext长度并禁用它是否为0或以其他方式启用它

回答by PothiraJ

When you want to disable the editText there You will use below code

当您想在那里禁用 editText 时,您将使用以下代码

editText.setEnabled(false); 
editText.setFocusable(false);

回答by Ashwin S Ashok

you check the status of an edittext at runtime using the text watcher. the below code counts the text length and disables if the length is zero. use this code:

您可以在运行时使用文本观察器检查 edittext 的状态。下面的代码计算文本长度并在长度为零时禁用。使用此代码:

EditText mEditText = new EditText(this);
    mEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub
            if (s.length() == 0) {
                button.setEnabled(false);
            }
                            else {
                            button.setEnabled(true);
                        }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });