2 kfcve123 kfcve123 于 2013.05.15 10:29 提问

android的edittext输入内容控制问题

效果见图,我想要实现模版名下的EditText输入内容的控制,只允许输入a-z A-Z 0-9 分号; 和汉字。以下是我自己的代码,都不能完全实现或是报错。求大神点拨

图片弄不上来,其实布局很简单,就是一个edittext和一个Button, 实现了edittext的输入要求,Button就可见并触发跳转事件

public class MainActivity extends Activity {
        private static String tag = "MainActivity";
        private Button btn;
        private EditText edt, content;
        private final int[] code = { 8, 13, 32, 48, 49, 50, 51, 52, 53, 54, 55, 56,
                        57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
                        81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 186 };
        private String digits = "0123456789abcdefghijklmnopqrstuvwxyz;";
        private String tmp;
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                btn = (Button) findViewById(R.id.btn_edit);
                btn.setEnabled(false);
                edt = (EditText) findViewById(R.id.edt);                
                edt.addTextChangedListener(edt_watcher);
                // edt.setOnKeyListener(input);
                btn.setOnClickListener(l);        
        }

//我的思路一:键盘监听事件,监听keyCode是否在允许的按键集合中, 
//但会出现如果我一按不在集合中的就会刷新之前已经输入过的内容
        OnKeyListener input = new OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // TODO Auto-generated method stub
                        for (int i = 0; i < code.length; i++) {
                                if (keyCode != code) {
                                        edt.setText(tmp);
                                        edt.invalidate();
                                }
                        }
                        return false;
                }
        };
//我的思路二:文本输入监听,在监听判断后我先获取到edt.gettext然后进行一个拼接处理,然后再设置回edittext的内容中
//会出现每次输入符合的字符会在左边添加,光标始终在最左边。 在处理上有问题, 看看这里能给出处理意见
        // 文本输入监听
        TextWatcher edt_watcher = new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                                int count) {
                        String str = s.toString();
                        String edttext = edt.getText().toString();
                        StringBuffer sb = new StringBuffer();
                        // TODO Auto-generated method stub
                        if (s.length() > 0 && str.matches("[a-zA-Z_0-9;]+")
                                        || str.matches("[\u4e00-\u9fa5]+")) {
                                sb = sb.append(s);
                                edt.setText(sb.toString());
                                Log.v(tag, sb.toString()+"======sb");
                                btn.setEnabled(true);
                        } else {
                                edttext = sb.append(tmp).toString();
                                Log.v(tag, edttext + "======edttext");
                                edt.setText(edttext);
                                tmp = str.substring(0,s.toString().length()-2);
                                edt.setText(tmp);
                                btn.setEnabled(false);
                        }        
                        Log.v(tag, s + "======s");
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                                int after) {

                        Log.v(tag, s + "======beforeTextChanged");
                }


//我的思路三:如下注释部分,但这里需要实现digits里包含所有的汉字,这里不知道怎么去弄
                @Override
                public void afterTextChanged(Editable s) {
                        // TODO Auto-generated method stub
                        Log.v(tag, s + "======afterTextChanged");
                        /*String str = s.toString();
                        if (str.equals(tmp)) {
                                return;
                                // 如果tmp==str则返回,因为这是我们设置的结果。否则会形成死循环。
                        }
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < str.length(); i++) {
                                if (digits.indexOf(str.charAt(i)) >= 0) {
                                        // 判断字符是否在可以输入的字符串中
                                        sb.append(str.charAt(i));
                                        // 如果是,就添加到结果里,否则跳过
                                }
                                tmp = sb.toString();// 设置tmp,因为下面一句还会导致该事件被触发
                                edt.setText(tmp);// 设置结果
                                edt.invalidate();
                        }
                        if ((str.matches("[a-zA-Z_0-9;]+") || str
                                        .matches("[\u4e00-\u9fa5]+"))) {
                                sb.toString().substring(str.length());
                        }
                        tmp = sb.toString();
                        edt.setText(tmp);
                        edt.invalidate();*/
                }
        };
        //判断输入的是不是汉字,没有用上的方法
         private boolean isChinese(char c) {
         Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
         if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
         || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
         || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
         || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
         || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
         || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
                 String edttext = edt.getText().toString();
                 StringBuffer sb = new StringBuffer(edttext);
                 sb.append(c);
                 edt.setText(sb);
         return true;
         }
         return false;
         }
        //判断是不是字母或者数字,分号,没有用上的方法,
         private boolean isRightData(CharSequence s) {
         if (s.toString().matches("[0-9;]+")
         || s.toString().matches("[a-zA-Z]+")) {
                 String edttext = edt.getText().toString();
                 StringBuffer sb = new StringBuffer(edttext);
                 sb.append(s);
                 edt.setText(sb);
                 edt.invalidate();
         return true;
         }
         return false;
         }

        OnClickListener l = new OnClickListener() {

                @Override
                public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(MainActivity.this, IldmActivity.class);
                        intent.putExtra("edt", edt.getText().toString());
                        startActivityForResult(intent, 10);
                        Log.v(tag, edt.getText() + "intent");
                }
        };

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
        }

        public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == 10 && resultCode == RESULT_OK) {

                }

        };

}

1个回答

MrsSeven7
MrsSeven7   2013.05.15 15:08

下面的代码可以实现只接受0-9数字

public static void setPhoneNumberFilter(final EditText edt, final int length) { InputFilter[] filters = new InputFilter[1];

    final int len = edt.getText().toString().length();
    Log.e("MIS", "" + edt.getText().toString());
    Log.e("MIS", "" + edt.getText().toString().length());
    if (len > length - 1) {
        return;
    }
    filters[0] = new InputFilter() {

        public CharSequence filter(CharSequence source, int start, int end,
                Spanned dest, int dstart, int dend) {
            // TODO Auto-generated method stub

            try {
                char[] acceptedChars = new char[] { '0', '1', '2', '3',
                        '4', '5', '6', '7', '8', '9' };
                for (int index = 0; index < end; index++) {

                    if (!new String(acceptedChars).contains(String
                            .valueOf(source.charAt(index)))
                            || edt.getText().toString().length() > length - 1) {
                        return "";
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    };
    edt.setFilters(filters);
}
setPhoneNumberFilter(edtxt,10);
Csdn user default icon
上传中...
上传图片
插入图片