如何根据输入的特定值更改 Android 上的 EditText?

How do you change an EditText on Android based on specific values inputted?

我希望用户更改某些设备设置,例如 运行 X 秒(默认 5 秒)后发出警报。我希望用户能够输入他们想要的内容(编辑文本中的数字值),但如果他们输入的值不在 2 到 20 秒之间,我希望编辑文本默认返回 5 秒。

最好的方法是什么?我试过观察者,但我想我 运行 进入了一个无限循环。

//Settings distance edit text
settings_distance_edit.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int settings_distance_edit_value = Integer.parseInt(settings_distance_edit.getText().toString()+"");
        if (settings_distance_edit_value >= DISTANCE_MIN && settings_distance_edit_value <= DISTANCE_MAX) {
            Log.v("Tag", settings_distance_edit_value+"");

        } else {
            settings_distance_edit.setText(DISTANCE_DEFAULT+"");
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

我想你可以这样做

  • 您可以在不使用 TextWatcher 的情况下检查值
    int settings_distance_edit_value = Integer.parseInt(settings_distance_edit.getText().toString()+"");
       if (settings_distance_edit_value >= DISTANCE_MIN && settings_distance_edit_value <= DISTANCE_MAX) {
          // you set your default value
     settings_distance_edit.setText("5s");

       } else {
           settings_distance_edit.setText(DISTANCE_DEFAULT+"");
       }

试试输入过滤器

public class InputFilterMinMax implements InputFilter
{
    private final int min;
    private final int max;
    private final UtilityListener utilityListener;

    public InputFilterMinMax(int min, int max,UtilityListener utilityListener)
    {
        this.min = min;
        this.max = max;
        this.utilityListener = utilityListener;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
    {
        try
        {
            int input = Integer.parseInt(dest.toString() + source.toString());

            if (isInRange(min, max, input))
            {
                return null;
            }
            else
            {
                utilityListener.getItem("Value cannot exceed " + max);
            }
        }
        catch (NumberFormatException ignored)
        {
            utilityListener.getItem("NumberFormatException");
        }
        return "";
    }

    private boolean isInRange(int a, int b, int c)
    {
    return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

Activity代码

binding.editText.setFilters(new InputFilter[]{new InputFilterMinMax(1,10,object ->
        {
            String message = (String) object;

            Toast.makeText(MainActivity.this,message,Toast.LENGTH_SHORT).show();
        })});

听众

public interface UtilityListener
{
    void getItem(Object object);
}
1.for integer input set your EditText digits="0123456789"
2. In if condition you should use || condition instead of &&
3. also check if input is not empty as given below.

this is working fine ,no infinite loop





   var MIN=2 
   var MAX=20 
   var DEF=5 
   et_distance.addTextChangedListener(object : TextWatcher { 
     override fun   onTextChanged(s: CharSequence?, start: Int,
     before: Int, count: Int) {

            if (et_distance.text.toString().isNotEmpty()) {
                var etValue = et_distance.text.toString().toInt()

                if (etValue >= MAX || etValue <= MIN){ 
                
                  
             et_distance.setText(DEF.toString())
               
             }
                else {
                   Log.d("TAG", "onTextChanged: $etValue")
                     }
            }
        }
        override fun beforeTextChanged(s: CharSequence?, 
                        start:Int,count: Int,  after: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
        }

    })

您不应将 addTextChangedListener() 用于此目的。 您应该等待用户按下键盘上的回车键或完成键。这可以通过以下代码实现:

settings_distance_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event != null && event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                if (event == null || !event.isShiftPressed()) {
                   // the user is done typing and has submitted the input. 

                   // your code
                   int settings_distance_edit_value = Integer.parseInt(settings_distance_edit.getText().toString()+"");
                   if (settings_distance_edit_value >= DISTANCE_MIN && settings_distance_edit_value <= DISTANCE_MAX) {
                      Log.v("Tag", settings_distance_edit_value+"");

                   } else {
                      settings_distance_edit.setText(DISTANCE_DEFAULT+"");
                   }

                   return true;
                }                
            }
            return false; // the user has not submitted the input yet. 
    }
});