How do I set a EditText to the input of only hexadecimal numbers?

后端 未结 3 1845
抹茶落季
抹茶落季 2020-12-29 08:17

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.         


        
3条回答
  •  天命终不由人
    2020-12-29 08:32

    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);
    

提交回复
热议问题