問題描述
我有一些代碼,如果 editText 字段中的字符少于 3 個(gè),我需要禁用創(chuàng)建帳戶"按鈕.如果用戶輸入 3 個(gè)字符,則該按鈕應(yīng)啟用自身以便可以使用.
I have some code where I need a "Create Account" button to be disabled if an editText field has less than 3 char in it. If the User enters 3 chars, then the button should enable itself so that it can be used.
我已經(jīng)構(gòu)建了 if else 語句,如果 editText 字段中的字符少于 3 個(gè),則禁用按鈕,但是在輸入時(shí),當(dāng)用戶插入 3 個(gè)字符時(shí),它不會(huì)重新評估該語句是否為真所以按鈕當(dāng)然會(huì)保持禁用狀態(tài).
I have constructed the if else statement that disables the button if there are less than 3 char in the editText field, BUT on input, when the user inserts 3 char, it does not re-evaluate to see if the statement is true so the button of course stays disabled.
一旦用戶在編輯文本字段中輸入 3 個(gè)字符,按鈕應(yīng)該會(huì)自行啟用.
Once the user enters 3 char into the edit text field, the button should enable itself.
Button buttonGenerate = (Button) findViewById(R.id.btnOpenAccountCreate);
userInitials = (EditText) findViewById(R.id.etUserChar);
if (userInitials.getText().toString().length() > 3) {
// Account Generator Button
buttonGenerate.setEnabled(true); // enable button;
buttonGenerate.setOnClickListener(new OnClickListener() {
//Do cool stuff here
@Override
public void onClick(View v) {
}
});// END BUTTON
} else {
// If UserInitials is empty, disable button
Toast.makeText(this, "Please enter three(3) characters in the Initials Field ", Toast.LENGTH_LONG)
.show();
buttonGenerate.setEnabled(false); // disable button;
}// END IF ELSE
推薦答案
你想使用一個(gè) TextWatcher
每當(dāng)您的 EditText
中具有此 listener
的文本發(fā)生更改時(shí),都會(huì)觸發(fā)此事件.您只需像其他任何 listener
一樣將 listener
附加到您的 EditText
然后覆蓋其方法,并從下面的鏈接示例中檢查長度
This will be triggered each time the text in your EditText
which has this listener
on it has changed. You just attach the listener
to your EditText
like you would any other listener
then override its methods and , from the linked example below, check the length
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s.length() > 2)
{
buttonGenerate.setEnabled(true);
}
else
{
buttonGenerate.setEnabled(true);
}
}
您不需要簽入您的 onClick()
然后,只需默認(rèn)禁用 Button
并在您的 onTextChanged()
如果滿足條件.
You don't need to check in your onClick()
then, just disable the Button
by default and enable in your onTextChanged()
if the condition is met.
重寫
上面可以清理為
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
buttonGenerate.setEnabled((s.length() > 2));
}
我也改成了>2
因?yàn)槲艺J(rèn)為這實(shí)際上是你想要的,但你擁有它的方式有點(diǎn)令人困惑.您說輸入三(3)",這聽起來正好是 3,但您的代碼看起來不同.無論如何,這對你來說很容易改變.
I also have changed it to > 2
because I think that's actually what you want but the way you have it is a little confusing. You say "enter three(3)" which sounds like exactly 3 but your code looks different. Anyway, that's easy enough for you to change.
查看這個(gè)答案的例子
這篇關(guān)于Android - 在用戶輸入之前和之后檢查editText是否> 3的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!