【问题标题】:Move focus to next EditText in an array将焦点移到数组中的下一个 EditText
【发布时间】:2015-04-24 08:32:19
【问题描述】:

我有一个活动,我从用户信用卡的序列号中获取。 它包含四个editTexts - 每个4 位数字。 我为 editTexts 使用了一个数组 -

EditText[] editSerial = new EditText[4];

我已经限制了每个editText中输入的长度

android:maxLength="4"

一旦用户在当前一个数字中输入了 4 个数字,我希望焦点移动到下一个 editText。 我已经看到了这个答案 - How to automatically move to the next edit text in android:

et1.addTextChangedListener(new TextWatcher() {

public void onTextChanged(CharSequence s, int start,int before, int count) 
{
    // TODO Auto-generated method stub
    if(et1.getText().toString().length()==size)     //size as per your requirement
    {
        et2.requestFocus();
    }
}

有没有比重复此代码 3 次更好的解决方案?

【问题讨论】:

  • 你可以使用一个编辑文本,这个link应该会有所帮助

标签: android


【解决方案1】:

有点。每个都需要一个 TextWatcher,但您可以将其提取为一个适当的类,以便您可以传入指示要关注的 View 的参数。

然后就变成这样了

et1.addTextChangedListener(new FocusSwitchingTextWatcher(et2));
et2.addTextChangedListener(new FocusSwitchingTextWatcher(et3));
et3.addTextChangedListener(new FocusSwitchingTextWatcher(et4));

班级:

private static class FocusSwitchingTextWatcher implements TextWatcher {

    private final View nextViewToFocus;

    TextWatcher(View nextViewToFocus) {
        this.nextViewToFocus = nextViewToFocus;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length > size) {
            nextViewToFocus.requestFocus();
        }
    }

    ... // the other textwatcher methods 

}

【讨论】:

  • *我会仔细检查要覆盖的实际 TextWatcher 方法,但我不记得每个参数实际上是什么
  • 谢谢,只有一件小事——该类应该实现 TextWatcher,而不是扩展它。我无法投票赞成这个答案,因为我的声誉太低了......
猜你喜欢
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 2014-06-30
  • 2021-11-08
  • 2020-04-02
  • 1970-01-01
  • 2016-06-30
  • 1970-01-01
相关资源
最近更新 更多