Search code examples
androidandroid-studioandroid-edittextrangehighlight

How to add a range in the EditText so that the input will highlight in red when typing if it goes out of range in Android Studio?


    eOUTPUT_VOLTAGE_L_N_V=(EditText)findViewById(R.id.bb_output_voltage_l_n_v_text);
    eLOAD_CURRENT_A=(EditText)findViewById(R.id.bb_load_current_a_text);
    eALARM_STATUS=(EditText)findViewById(R.id.bb_alarm_status_text);
    eSTATUS=(EditText)findViewById(R.id.bb_status_text);
    eREMARK=(EditText)findViewById(R.id.bb_remark_text);

Specifically I want to limit the values to be entered into the edit text by highlighting in red when typing if it goes out of range. For an example I want to input a numerical range like 200v - 400v for the eOUTPUT_VOLTAGE_L_N_V so that the typing text would highlight in red when user typing a out of range value like 600v.


Solution

  •   eOUTPUT_VOLTAGE_L_N_V.addTextChangedListener(new TextWatcher() {
                   @Override
                   public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                   }
    
                   @Override
                   public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                           if(Integer.parseInt(s.toString()) > 400){
                                 eOUTPUT_VOLTAGE_L_N_V.setError("something");
                            }
    
                   }
    
                   @Override
                   public void afterTextChanged(Editable s) {
    
                   }
               });