EditText篇

来源:互联网 发布:html砸金蛋源码下载 编辑:程序博客网 时间:2024/06/13 08:55
一、EditText不可编辑
两种选择:第一个 不可编辑但是会弹出输入法android:editable="false" 第二个 不可编辑同时不会弹出输入法android:focusable="false"
二、EditText设置输入限制
android:digits="1234567890.+-*/%\n()"限制输入框中只能输入自己定义的这些字符串 如果输入其它将不予以显示android:phoneNumber="true"限制输入框中只能输入手机号码android:password="true"限制输入框中输入的任何内容将以"*"符号来显示android:hint="默认文字"输入内容前默认显示在输入框中的文字android:textColorHint="#FF0000"设置文字内容颜色
三、EditText的监听事件
给EditText添加一个监听事件,当检测到里面的内容变化以后,根据需求,修改相关的内容就可以了。
使用EditText的addTextChangedListener(TextWatcher watcher)方法对EditText实现监听,TextWatcher是一个接口类,所以必须实现TextWatcher里的抽象方法:
当EditText里面的内容有变化的时候,触发TextChangedListener事件,就会调用TextWatcher里面的抽象方法。

public class MainActivity extends Activity {     private EditText text;     String str;     @Override    public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);                  text = (EditText)findViewById(R.id.text);         text.addTextChangedListener(textWatcher);     }          private TextWatcher textWatcher = new TextWatcher() {                  @Override           public void afterTextChanged(Editable s) {                // TODO Auto-generated method stub               Log.d("TAG","afterTextChanged--------------->");          }                   @Override        public void beforeTextChanged(CharSequence s, int start, int count,                 int after) {             // TODO Auto-generated method stub            Log.d("TAG","beforeTextChanged--------------->");         }          @Override           public void onTextChanged(CharSequence s, int start, int before,                    int count) {                Log.d("TAG","onTextChanged--------------->");               str = text.getText().toString();             try {                 //if ((heighText.getText().toString())!=null)                 Integer.parseInt(str);             } catch (Exception e) {                 // TODO: handle exception            }                                      }                       };}

该方法可以监听到Edittext的变化,我在onTextChanged里面监听s值得变化,然后做修改以后再setText到EditText里面,不过这时候经常会遇见光标跑到最前面的情况,很恶心,随意每次setText的时候都需要用ev.setSelection(str.length())去重新设置光标位置为str字符串的最后。
1 0
原创粉丝点击