首先在这里设置我在 xml 文件中EditText max length=1
取三个。EditText
<EditText
android:id="@+id/edt1"
android:layout_width="40dp"
android:layout_height="40dp"
android:inputType="number"
android:textAlignment="center"
android:singleLine="true"
android:maxLength="1"
android:maxLines="1"
android:imeOptions="actionNext"
android:layout_margin="5dp"
android:background="@drawable/edittext_shape_bg"/>
<EditText
android:id="@+id/edt2"
android:layout_width="40dp"
android:layout_height="40dp"
android:inputType="number"
android:textAlignment="center"
android:singleLine="true"
android:maxLength="1"
android:imeOptions="actionNext"
android:maxLines="1"
android:layout_margin="5dp"
android:background="@drawable/edittext_shape_bg"/>
<EditText
android:id="@+id/edt3"
android:layout_width="40dp"
android:layout_height="40dp"
android:inputType="number"
android:textAlignment="center"
android:singleLine="true"
android:maxLength="1"
android:imeOptions="actionNext"
android:maxLines="1"
android:layout_margin="5dp"
android:background="@drawable/edittext_shape_bg"/>
然后addTextChangeListener
在每个EditText
帮助您前进和后退的实施后。
这里我们StringBuilder
用来获取最终字符串值。
edt1.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) {
String edtChar=edt1.getText().toString();
if(edtChar.length()==1)
{
currentCode.append(edtChar);
edt2.requestFocus();
}else if(edtChar.length()==0) {
currentCode.deleteCharAt(0);
edt1.requestFocus();
}
}
});
edt2.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) {
String edtChar=edt2.getText().toString();
if(edtChar.length()==1)
{
currentCode.append(edtChar);
edt3.requestFocus();
}else if(edtChar.length()==0) {
currentCode.deleteCharAt(1);
edt1.requestFocus();
}
}
});
edt3.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) {
String edtChar=edt3.getText().toString();
if(edtChar.length()==1)
{
currentCode.append(edtChar);
edt4.requestFocus();
}else if(edtChar.length()==0) {
currentCode.deleteCharAt(2);
edt2.requestFocus();
}
}
});