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

一,布局文件
    
    

二,java文件


/**
 * 限定EditText只能输入最多两位小数
 * @author Administrator
 *
 */
public class MainActivity extends ActionBarActivity {

	private EditText num_et;
	private EditText num_et2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		num_et = (EditText) findViewById(R.id.num_et);
		num_et2 = (EditText) findViewById(R.id.num_et2);
		/**
		 * 第一种方法
		 */
		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
                 
            }
 
        });
		/**
		 * 第二种方法
		 */
		num_et2.addTextChangedListener(new TextWatcher() 
		  {
		      public void afterTextChanged(Editable edt) 
		      {
		          String temp = edt.toString();
		          int posDot = temp.indexOf(".");
		          if (posDot <= 0) return;
		          if (temp.length() - posDot - 1 > 2)
		          {
		              edt.delete(posDot + 3, posDot + 4);
		          }
		      }

		      public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

		      public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
		  });
	}
}


你可能感兴趣的:(android,EditText)