首页 > 解决方案 > 当在键盘上按下特定字符时,我可以切换到另一个 EditText 吗?

问题描述

我的应用中有 3 个 EditText。我想这样做,如果用户在 EditText1 中输入并按空格键,他将被“发送”到第二个 EditText,从 EditText2 到 EditText3 也是如此。但是,当在 EditTexts 中给出一个空格时,它不应该出现。

这可能吗?我该怎么做?

标签: androidandroid-studiokotlin

解决方案


Yes sure you can use TextWatcher

Java version

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

        if (s != null && s.endsWith("Your_special_char")){
          yourDesiredEditText.requestFocus();
        }
    }

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

    @Override
    public void afterTextChanged(Editable s) {}
});

Kotlin version

et1.addTextChangedListener(object : TextWatcher {
  override fun afterTextChanged(p0: Editable?) {
  }

  override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
  }

  override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
      if (p0?.endsWith("Your_special_char") == true){//it will eliminate nullability (trick)
          yourDesiredEditText.requestFocus()
        }
  }
})

EDIT

the only issue is I have with this is you end up with a ton of code in each event.

Ok I will provide a clean and neat solution using Kotlin extension functions

fun EditText.forwardFocusOnSpecialCharEntered(targetEditText: EditText) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {}
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            if (p0?.endsWith(" ") == true) targetEditText.requestFocus()
        }
    })
}

Usage

firstEditText.forwardFocusOnSpecialCharEntered(secondEditText)
secondEditText.forwardFocusOnSpecialCharEntered(thirdEditText)
thirdEditText.forwardFocusOnSpecialCharEntered(firstEditText)
 

Now using one line of code you can achieve your goal as well as your code stays clean and readable


推荐阅读