天使漫步IT工作室天使漫步IT工作室

android限定EditText只能输入两位小数的两种方式


Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 110

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 116

EditText提供的API并不能满足需求,所以需要在代码中写出限定规则。

<br/>

1、布局文件样式

首先在EditText中设置android:numeric="decimal",限定输入格式为double类型。

代码示例如下:

<EditText  
    android:id="@+id/num_et"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:numeric="decimal"/>  

<br/>

2、通过addTextChangedListener监听输入

在OnCreate方法中获取实例:

num_et = (EditText) findViewById(R.id.num_et); 

在代码中注册监听:


        num_et.addTextChangedListener(new TextWatcher() {  
               
            @Override  
            public void onTextChanged(CharSequence s, int start, int before,  
                    int count) {  
                if (s.toString().contains(".")) {  
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {  
                        s = s.toString().subSequence(0,  
                                s.toString().indexOf(".") + 3);  
                        num_et.setText(s);  
                        num_et.setSelection(s.length());  
                    }  
                }  
                if (s.toString().trim().substring(0).equals(".")) {  
                    s = "0" + s;  
                    num_et.setText(s);  
                    num_et.setSelection(2);  
                }  
   
                if (s.toString().startsWith("0")  
                        && s.toString().trim().length() > 1) {  
                    if (!s.toString().substring(1, 2).equals(".")) {  
                        num_et.setText(s.subSequence(0, 1));  
                        num_et.setSelection(1);  
                        return;  
                    }  
                }  
            }  
   
            @Override  
            public void beforeTextChanged(CharSequence s, int start, int count,  
                    int after) {  
   
            }  
   
            @Override  
            public void afterTextChanged(Editable s) {  
                // TODO Auto-generated method stub  
                   
            }  
   
        });  

本站原创,欢迎转载,转载敬请标明出处:天使漫步IT工作室 » android限定EditText只能输入两位小数的两种方式
添加新评论


Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /www/wwwroot/u11u.com/usr/themes/wq/comments.php on line 38