如何在指定的EditText到达限制时自动将Focus从一个EditText切换到另一个EditText(android)

时间:2016-02-17 03:49:16

标签: android

我发现当指定的EditText没有设置“addTextWatcher”时, 以下操作无效: editText1.clearFocus(); editText2.requestFocus();

我的目的是将光标移动到editText2,但它不起作用,我该如何解决这个问题

2 个答案:

答案 0 :(得分:0)

看看这个例子。

假设有4 EditText

EditTextV pin1 = (EditText) indViewById(R.id.pin1);
EditTextV pin2 = (EditText) indViewById(R.id.pin2);
EditTextV pin3 = (EditText) indViewById(R.id.pin3);
EditTextV pin4 = (EditText) indViewById(R.id.pin4);

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

pin1.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (s.toString().trim().length() != 0) // You can specify some specific length here e.g suppose you want length 4 then s.toString().trim().length() != 4
        pin2.requestFocus();
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});
pin2.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (s.toString().trim().length() != 0)
        pin3.requestFocus();
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});
pin3.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (s.toString().trim().length() != 0) 
        pin4.requestFocus();
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

pin4.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.toString().trim().length() != 0) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(pin4.getWindowToken(), 0);                  
        }
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

答案 1 :(得分:0)

YourEditText.addTextChangedListener(new TextWatcher() {
   @Override
   public void onTextChanged(CharSequence s, int start, int before, int count) {

      if (!(s.toString().trim().length() == 0))
          YourEdidtText2.requestFocus();
      }
   }
  .
  .
  .
  .
  .
});

这可能会帮助你