[英]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.