如果有很多的话,如何关注下一个edittext

时间:2018-08-22 13:29:53

标签: android

如果我必须转到下一个EditText,我必须在布局中使用多个EditText,我必须在其中包含以下代码的情况下使用et1.addTextChangedListener

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (et1.getText().toString().length() == 1) {
        et2.requestFocus();
    }
}

我非常了解,但是问题是我有17到20个EditText,如果我继续为每个EditText编写代码,我的代码将是最糟糕的代码。接下来的十年该如何处理?

我的情况非常具体:当用户按下键盘上的某个键时,他只需要关注下一个EditText。没有ACTION_UPACTION_DOWN

2 个答案:

答案 0 :(得分:0)

create a function that gets the first and second edittexts and check

    public void goToAnotherEditext(final EditText et1, final EditText et2){
    et1.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void afterTextChanged(Editable editable) {

            if(et1.getText().toString().trim().length()==1){
                et2.requestFocus();
            }
        }
    });
}

then put the edittexts inside the function

 EditText et1 = new EditText(getApplicationContext());
    EditText et2 = new EditText(getApplicationContext());

    goToAnotherEditext(et1,et2);

答案 1 :(得分:0)

In your XML file, what you can do is make your edittext,

android:singleLine="true"

and you can then add imeOptions to change your current focus to next edittext,

android:imeOptions="actionNext"

imeOptions are used to navigate to next action item focusable. to know in deep use other attribute values of imeOptions.

In this way, you don't need to make your hands dirty by performing programatical part. you can easily do this by XML Part. I hope this is helpful to you.