EditText小结

来源:互联网 发布:windows 10 版本 1607 编辑:程序博客网 时间:2024/06/05 02:42
EditText是Android开发经常用到的控件之一,其属性众多,特殊属性小结如下:

1. 设置光标到指定位置   EditText et = (EditText) findViewById(R.id.etTest);
   et.setSelection(2);

2. 隐藏光标   EditText et = (EditText) findViewById(R.id.etTest);
   //设置光标不显示,但不能设置光标颜色
   et.setCursorVisible(false);

3. 获得焦点时全选文本
   EditText et = (EditText) findViewById(R.id.etTest);
   et.setSelectAllOnFocus(true);

4. 获取和失去焦点   EditText et = (EditText) findViewById(R.id.etTest);
   et.requestFocus(); //请求获取焦点
   et.clearFocus(); //清除焦点

5.点击EditText不弹出软键盘
   EditText editET = (EditText) findViewById(R.id.etTest);
   editET.setOnTouchListener(new OnTouchListener() {
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    int inType = editET.getInputType(); // backup the input type
    editET.setInputType(InputType.TYPE_NULL); // disable soft input
    editET.onTouchEvent(event); // call native handler
    editET.setInputType(inType); // restore input type
    editET.setSelection(editET.getText().length());
    return true;
   }
  });

6.只能输入数字     EditText et = (EditText) findViewById(R.id.etTest);
   et.setInputType(InputType.TYPE_CLASS_NUMBER);

7.只能输入电话号码
   EditText et = (EditText) findViewById(R.id.etTest);
   et.setInputType(InputType.TYPE_CLASS_PHONE);

8.邮箱地址   EditText et = (EditText) findViewById(R.id.etTest);
   et.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);

9.输入错误提示(图9)
   EditText et = (EditText) findViewById(R.id.etTest);
   et.setError("有错误提示");

10.自定义错误提示(图10)

   Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
   d.setBounds(0, 0, 30, 30); //必须设置大小,否则不显示
   et.setError("有错误提示", d);
原创粉丝点击