英文:
Is there a way to define a min and max value for a EditText. EG 20 - 200 (not starting at 1)
问题
我一直在各处看到这个示例,我试图找到一种定义`EditText`的最小和最大值的方法。我有点理解它的功能,但我发现如果最小值大于10,它就会出错。有没有办法修改这段代码,使最小值可以是任何数字?还有没有更简单的方法来做到这一点,因为这似乎对于一个简单的任务来说过于复杂了?
ClassName.setFilters(new InputFilter[]{new InputFilterMinMax("1", "200")});
class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
英文:
I keep seeing this example everywhere I look to find a way to define the min and max of a EditText
. I kind of understand what it does but I found that it breaks if the min is bigger then 10. Is there any way this code could be changed so that the min can be any number? And is there any easier way of doing this as it seems to be over-complicated for a simple task?
ClassName.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "200")});
class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
答案1
得分: 1
会有一些事件,这里我正在处理按钮点击事件
@Override
public void onClick(View view) {
String guessSize = editText.getText().toString();
if (Integer.parseInt(guessSize) <= 20 || Integer.parseInt(guessSize) >= 200)
{
// 你想要的任何操作
Toast.makeText(MainActivity.this, "不正确", Toast.LENGTH_SHORT).show();
}
英文:
there will be some event, Here I'm taking button click event
@Override
public void onClick(View view) {
String guessSize=editText.getText().toString();
if(Integer.parseInt(guessSize)<=20 || Integer.parseInt(guessSize)>=200)
{
//Anything you want
Toast.makeText(MainActivity.this, "No wroking", Toast.LENGTH_SHORT).show();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论