Android如何在单击退格时关注另一个edittext

时间:2015-10-28 08:03:22

标签: android

我正在尝试让Pin进入页面,我创建了4个EditTexts,并在我的活动中创建了一个函数。我的问题是,当我单击退格按钮时,我想将当前EditText聚焦到Before(Back)EditText,但Key监听器不起作用。

逻辑很简单,当用户输入一个编号来编辑文本时,它会失去焦点,然后编辑文本会得到焦点,然后就是这样。但问题是当我点击后退空间我想在edittext之前返回再次输入数字。我试图在beforeTextChange中插入keyListener,但它没有工作。

 private void SetTextChange(final EditText etCurrent, final EditText etForward,final EditText etBack, final boolean isLast, final int currentPosition)
{

    etCurrent.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

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

            if (etCurrent.getText().length() == 1 && !isLast ) {
                etCurrent.setTypeface(null, Typeface.NORMAL);
                etCurrent.clearFocus();
                etForward.requestFocus();
                etForward.setCursorVisible(true);

                etCurrent.getBackground().setColorFilter(getResources().getColor(R.color.lavender_indigo), PorterDuff.Mode.SRC_ATOP);
            } else if (etCurrent.length() == 0) {
                etCurrent.getBackground().setColorFilter(getResources().getColor(R.color.french_gray), PorterDuff.Mode.SRC_ATOP);
                etCurrent.setTypeface(null, Typeface.SANS_SERIF.getStyle());

                etCurrent.setTypeface(null, Typeface.NORMAL);
                etCurrent.clearFocus();
                etBack.requestFocus();
                etBack.setCursorVisible(true);

            }


            if (etCurrent.length() != 0) {
                Integer currentKey = Integer.parseInt(etCurrent.getText().toString());
                keyList.set(currentPosition, currentKey);
            } else
                keyList.set(currentPosition, -1);

            if (keyList.size() > 3)
                showToast(keyList.get(0) + " " + keyList.get(1) + " " + keyList.get(2) + " " + keyList.get(3));

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    /*curText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View arg0, boolean arg1) {
            curText = etCurrent;
            backText = etBack;
            curText.setText("");
        }

        });*/
    }

这也是我的EditText示例xml之一。(其他是相同的)

  <EditText
        android:layout_column="1"
        android:layout_columnWeight="1"
        android:id="@+id/etActivationDigit1"
        android:layout_width="70dp"
        android:layout_height="wrap_content"
        android:textSize="80dp"
        android:textAlignment="center"
        android:gravity="center_horizontal"
        android:hint="*"
        android:textColorHint="@color/french_gray"
        android:backgroundTint="@color/french_gray"
        android:fontFamily="sans-serif"
        android:textColor="@color/perfume"
        android:maxLength="1"
        android:inputType="number"
         />

我只是想在用户输入错误号码时擦除并重新聚焦。注意:当你填写所有字段时,你会看到你可以删除并返回,但我想回到密码的中间位置。谢谢。

  etCurrent.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if(etCurrent.getText().toString() == "" && keyCode == event.KEYCODE_DEL)
            {
                etCurrent.setText("");
                etCurrent.clearFocus();
                etBack.requestFocus();
                etBack.setText("");
            }
            return false;
        }
    });

当我触摸退格键时,我的Backspace侦听器不会触发,但会触发所有其他字符。

6 个答案:

答案 0 :(得分:2)

这适用于我的4位密码活动。

private void setupInputListeners() {
    verificationCode1EditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() == 1) {
                verificationCode2EditText.requestFocus(View.FOCUS_DOWN);
            }
        }

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

    verificationCode2EditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(count == 0) {
                verificationCode1EditText.requestFocus(View.FOCUS_DOWN);
            } else {
                if (s.length() == 1) {
                    verificationCode3EditText.requestFocus(View.FOCUS_DOWN);
                }
            }
        }

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

    verificationCode3EditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(count == 0) {
                verificationCode2EditText.requestFocus(View.FOCUS_DOWN);
            } else {
                if (s.length() == 1) {
                    verificationCode4EditText.requestFocus(View.FOCUS_DOWN);
                }
            }
        }

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

    verificationCode4EditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(count == 0) {
                verificationCode3EditText.requestFocus(View.FOCUS_DOWN);
            }
        }

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

答案 1 :(得分:0)

看看这个。
MainActivity.java

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText one = (EditText) findViewById(R.id.edtOne);
        final EditText two = (EditText) findViewById(R.id.edtTwo);
        final EditText three = (EditText) findViewById(R.id.edtThree);
        final EditText four = (EditText) findViewById(R.id.edtFour);

        one.addTextChangedListener(new TextWatcher() {

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

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

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

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                if(s.toString().trim().length() == 0){
                    one.requestFocus();
                    one.setSelection(one.getText().toString().length());
                }

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

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

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                if(s.toString().trim().length() == 0){
                    two.requestFocus();
                    two.setSelection(two.getText().toString().length());
                }

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

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

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                if(s.toString().trim().length() == 0){
                    three.requestFocus();
                    three.setSelection(three.getText().toString().length());
                }

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });


    }


}

//使用此代码作为参考。

customDialog.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                if (event.getAction() != KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        customDialog.dismiss();
                        HomeActivity.this.finish();
                    } else if (keyCode == KeyEvent.KEYCODE_DEL) {
                        if (!pin3.getText().toString().equals("")) {
                            pin3.setText("");
                            pin3.requestFocus();
                        } else if (!pin2.getText().toString().equals("")) {
                            pin2.setText("");
                            pin2.requestFocus();
                        } else if (!pin1.getText().toString().equals("")) {
                            pin1.setText("");
                            pin1.requestFocus();
                        }
                    }
                }
                return true;
            }
        });
        return customDialog;

我在我的应用程序中使用此代码,它完全有效。

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <EditText
        android:id="@+id/edtOne"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="0" />
    <EditText
        android:id="@+id/edtTwo"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="2" />
    <EditText
        android:id="@+id/edtThree"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="3" />
    <EditText
        android:id="@+id/edtFour"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="4" />

</LinearLayout>

答案 2 :(得分:0)

只需将此代码添加到您的editText onTextChanged方法中

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(yourEditText.length()==0){
                priviousEditText.requestFocus();
            }
}

答案 3 :(得分:0)

    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {


    if (keyCode == KeyEvent.KEYCODE_DEL) {
        if (mPineighthDigitEditText.getText().length() ==0 )
        {       //mPineighthDigitEditText.setText("");
            mPinseventthDigitEditText.requestFocus();
    }
          if (mPinseventthDigitEditText.getText().length() == 0){
           // mPinseventthDigitEditText.setText("");
            mPinsixthDigitEditText.requestFocus();}
          if (mPinsixthDigitEditText.getText().length() == 0) {
           // mPinsixthDigitEditText.setText("");
            mPinFifthDigitEditText.requestFocus();}
         if (mPinFifthDigitEditText.getText().length() == 0){
            //mPinFifthDigitEditText.setText("");
            mPinForthDigitEditText.requestFocus();}
         if (mPinForthDigitEditText.getText().length() == 0){
           // mPinForthDigitEditText.setText("");
            mPinThirdDigitEditText.requestFocus();}
          if (mPinThirdDigitEditText.getText().length() == 0){
            //mPinThirdDigitEditText.setText("");
          mPinSecondDigitEditText.requestFocus();}
         if (mPinSecondDigitEditText.getText().length() == 0){
            //mPinSecondDigitEditText.setText("");
            mPinFirstDigitEditText.requestFocus();}
          if (mPinFirstDigitEditText.getText().length() == 0 ) {
              mPinFirstDigitEditText.setText("");
          }
        return true;
    }

    return super.onKeyDown(keyCode, event);


}

}

如果提交了多个编辑文本,谢谢:)

答案 4 :(得分:0)

以为 OTP 填充 4 个 editText 的示例编写此答案。

首先创建一个包含 4 个 editText 的数组并将它们与视图绑定

private var otpPins = arrayOfNulls<EditText>(4) //remember to input maxlenght = 1 in each view in xml file

otpPins[0] = findViewById(R.id.otp_1)
otpPins[1] = findViewById(R.id.otp_2)
otpPins[2] = findViewById(R.id.otp_3)
otpPins[3] = findViewById(R.id.otp_4)

然后添加textWatcher,这样当输入任意数字时焦点会改变到下一个editText

otpPins[0]?.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            if (s?.length ?: 0 >= 1) {
                otpPins[1]?.requestFocus()
            }
        }
    })

    otpPins[1]?.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            if (s?.length ?: 0 >= 1) {
                otpPins[2]?.requestFocus()
            }
        }
    })

    otpPins[2]?.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            if (s?.length ?: 0 >= 1) {
                otpPins[3]?.requestFocus()
            }
        }
    })

    otpPins[3]?.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            if (s?.length ?: 0 >= 1) {
                verifyOtpAndProceed()
            }
        }
    })

现在创建 1 个内部类来检测退格键并将焦点更改为之前的 editText

inner class PinOnKeyListener internal constructor(private val currentIndex: Int) :
    View.OnKeyListener {
    override fun onKey(v: View, keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_DEL && event.action == KeyEvent.ACTION_DOWN) {
            if (otpPins[currentIndex]?.text.toString()
                    .isEmpty() && currentIndex != 0
            ) otpPins[currentIndex - 1]?.requestFocus()
        }
        return false
    }
}

为每个 editText 分配 setOnKeyLister

otpPins[0]?.setOnKeyListener(PinOnKeyListener(0))
otpPins[1]?.setOnKeyListener(PinOnKeyListener(1))
otpPins[2]?.setOnKeyListener(PinOnKeyListener(2))
otpPins[3]?.setOnKeyListener(PinOnKeyListener(3))

最终结果将是当您输入任何数字时,焦点将更改为下一个图钉。当按下退格键时,如果有输入,它会简单地擦除它,如果没有输入,它会移动到前一个引脚。

答案 5 :(得分:-1)

只需使用StringBuilder并在此处注明您想要关注退格的editText,如下所示:

StringBuilder sb = new StringBuilder(); //define this inside addTextChangedListner 

public void afterTextChanged (Editable s) {
    if (sb.length() == 0) {
        previousEditText.requestFocus();
    }
}