[英]How to show different Message for different input length in EditText?
我想向用戶顯示一些不同的消息,以說明他們輸入的不同長度。 但是我的代碼無法正常工作。 怎么了
EditText boxID = findViewById(R.id.vcInput);
Button button = findViewById(R.id.refresh);
TextView tv = findViewById(R.id.message)
final int inputLength = boxID.getText().toString().length();
if(inputLength >= 10 && inputLength <= 11)
{tv.setText("Refresh request sent");}
else if(inputLength<1)
{tv.setText("VC number field looks empty");} //Only this one works at any input length
else if(inputLength>1 && inputLength<10)
{tv.setText("VC number must be at least 10 digit");}
else {tv.setText("Wrong input");}
您正在尋找的可能是TextWatcher
使用示例:
boxID.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
int inputLength = s.length();
if(inputLength >= 10 && inputLength <= 11)
{tv.setText("Refresh request sent");}
else if(inputLength<1)
{tv.setText("VC number field looks empty");}
else if(inputLength>1 && inputLength<10)
{tv.setText("VC number must be at least 10 digit");}
else {tv.setText("Wrong input");}
});
您的inputLength
是final
。 最初,inputLength為空,並將其保存到最終字段inputLength
,值為0。這就是為什么僅觸發第二個條件的原因。
在觸發onClick
之前已設置了inputLength
值。
一種解決方案是使用TextWatcher
或更簡單的解決方案是將inputLength
移到onClick
,這樣,您可以為每個onClick
觸發器獲取inputLength的新值:
@Override
public void onClick(View v) {
final int inputLength = boxID.getText().toString().length();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(inputLength >= 10 && inputLength <= 11)
tv.setText("Refresh request sent");
else if(inputLength<1)
tv.setText("VC number field looks empty"); //Only this one works at any input length
else if(inputLength>1 && inputLength<10)
tv.setText("VC number must be at least 10 digit");
else tv.setText("Wrong input");
}
})
}
好吧,您有3個條件(實際上是4個)
inputLength >= 10 && inputLength <= 11
inputLength<1
inputLength>1 && inputLength<10
else
您可以這樣:
if(inputLength >= 10 && inputLength <= 11)
{tv.setText("Refresh request sent");}
if(inputLength<1)
{tv.setText("VC number field looks empty");}
if(inputLength>1 && inputLength<10)
{tv.setText("VC number must be at least 10 digit");}
if(inputLength > 11)
{tv.setText("Wrong input");}
我在else if
語句中也遇到過類似的問題。 我不得不重建條件樹。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.