3
I created a screen with 2 fields EditText
, one with numerical input and another text. What I want is to execute a validation in the first field when it loses focus, and if invalid, return the focus to this first field to be written.
The problem is when I use .requestfocus()
, the two fields stay with the focus cursor, even using .clearfocus()
in the second field, the cursor is only in the first but if I type something it takes the keyboard and the input of the data in the second field.
For me it should be obvious when requesting the focus of a field, this be selected assuming its settings and automatically disable the other. I put down a very simple example. I thank anyone who can enlighten me.
package com.example.android.teste;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText numero, texto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numero = findViewById(R.id.editText);
texto = findViewById(R.id.editText2);
numero.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (!b) {
//Executo uma validação e conforme resultado inválido retorno no campo para redigitar.
numero.requestFocus();
}
}
});
}
}
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />