自定义TextWatcher
package com.example.day_05;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
public class JumpTextWtacher implements TextWatcher {
private EditText editText;
private View view;
public JumpTextWtacher(EditText editText,View view){
super();
this.editText=editText;
if(view!=null)this.view=view;
}
@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 str = editable.toString();
if(str.contains("\r")||str.contains("\n")){
editText.setText(str.replace("\r","").replace("\n",""));
if(view!=null){
view.requestFocus();
if(view instanceof EditText){
EditText e =(EditText)view;
e.setSelection(e.getText().length());
}
}
}
}
}
MainActivity
package com.example.day_05;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editText=findViewById(R.id.editTextTextPassword);
EditText editText1 = findViewById(R.id.editTextTextPassword2);
editText.addTextChangedListener(new JumpTextWtacher(editText,editText1));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextTextPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:maxLength="8"
android:hint="@string/password"
android:importantForAutofill="no"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editTextTextPassword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints=""
android:ems="10"
android:hint="@string/edittext2"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPassword" />
</androidx.constraintlayout.widget.ConstraintLayout>