在范围EDITTEXT值 [英] EditText Values in range

查看:94
本文介绍了在范围EDITTEXT值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在输入范围内的值,例如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>
 

解决方案

您可以指定一个 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.

这篇关于在范围EDITTEXT值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆