如何将EditText设置为仅十六进制数字的输入? [英] How do I set a EditText to the input of only hexadecimal numbers?

查看:358
本文介绍了如何将EditText设置为仅十六进制数字的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会将这段代码放在EditText上,以使其仅接受十六进制数字. 我该怎么做呢?

I would put in this code a control on EditText so that it only accepts hexadecimal numbers. How do I go about doing this?

bin = (EditText)findViewById(R.id.editText02);
hex = (EditText)findViewById(R.id.editText3);
dec = (EditText)findViewById(R.id.editText1);
oct = (EditText)findViewById(R.id.editText04);

推荐答案

TextWatcher也是不错的选择,但是我更喜欢使用自定义过滤器. 因此,更简单的方法是使用InputFilter并即时控制每个字符,请参见下面的示例,希望对您有所帮助

TextWatcher is also good option, however I prefer using custom filters. thereby, simpler way is to use InputFilter and take control of every char on the fly, see example below, hope this helps

    import android.text.InputFilter;
    import android.text.InputType;

    EditText input_moodMsg; 
    // initialize this edittext etc etc
    //....
    // here comes the filter to control input on that component
    InputFilter inputFilter_moodMsg = new InputFilter() {
                @Override
                public CharSequence filter(CharSequence source, int start, int end,Spanned dest, int dstart, int dend) {

                    if (source.length()>44) return "";// max 44chars

// Here you can add more controls, e.g. allow only hex chars etc

                    for (int i = start; i < end; i++) { 
                         if (!Character.isLetterOrDigit(source.charAt(i)) && !Character.isSpaceChar(source.charAt(i))
                                 && source.charAt(i)!='-'
                                 && source.charAt(i)!='.'
                                 && source.charAt(i)!='!'
                                 ) { 
                             return "";     
                         }     
                    }
                    return null;   
                }
            };
            input_moodMsg.setFilters(new InputFilter[] { inputFilter_moodMsg });
            input_moodMsg.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

这篇关于如何将EditText设置为仅十六进制数字的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆