在范围EDITTEXT值范围、EDITTEXT

2023-09-04 23:40:30 作者:Reset(重来)

我想在输入范围内的值,例如1-60。该的EditText 不应该接受像61,62 ......,或0,-1值,-2 ...

我们如何能够给在Android上的范围为1-60 的EditText ? 我在main.xml中完成的

 < EditText上安卓layout_height =WRAP_CONTENT
    机器人:ID =@ + ID / editText1
    机器人:layout_width =160dip
    机器人:inputType =数字>
    < /的EditText>
 

解决方案 android EditText传值到另一界面,不能用intent.putExtra去传值

您可以指定一个 TextWatcher 的EditText 并聆听文字的变化出现,例如:

 公共无效afterTextChanged(编辑S){
   尝试 {
     INT VAL =的Integer.parseInt(s.toString());
     如果(VAL→60){
        s.replace(0,s.length(),60,0,2);
     }否则如果(VAL< 1){
        s.replace(0,s.length(),1,0,1);
     }
   }赶上(NumberFormatException的前){
      // 做一点事
   }
}
 

正如刚才Devunwired,通知,调用 s.replace()将再次调用TextWatcher递归。

这是典型的包装这些变化对一个布尔编辑标志的检查,以便递归调用跳过并简单地返回而来自内部的变化。

I would like to enter the values in a range like 1-60. The EditText shouldn't accept values like 61,62..., or 0,-1,-2...

How can we give the range 1-60 to EditText in android? I have done in main.xml as

 <EditText android:layout_height="wrap_content" 
    android:id="@+id/editText1" 
    android:layout_width="160dip" 
    android:inputType="number">
    </EditText>

解决方案

You can assign a TextWatcher to your EditText and listen for text changes there, for example:

public void afterTextChanged(Editable s) {
   try {
     int val = Integer.parseInt(s.toString());
     if(val > 60) {
        s.replace(0, s.length(), "60", 0, 2);
     } else if(val < 1) {
        s.replace(0, s.length(), "1", 0, 1);
     }
   } catch (NumberFormatException ex) {
      // Do something
   }
}

As mentioned by Devunwired, notice that calls to s.replace() will call the TextWatcher again recursively.

It is typical to wrap these changes with a check on a boolean "editing" flag so the recursive calls skip over and simply return while the changes that come from within.