EditText 不聚焦,并且在一次输入后隐藏键盘后不显示键盘

EditText not focusing, and not showing keyboard after keyboard is hidden after one input

我正在实施一个 OTP 验证 系统并且在我的布局中有 3 个 EditText 字段,其中一个在用户单击按钮之前是隐藏的。 这是布局文件:

registration_acivity_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=".RegistrationActivity">

    <ImageView
         />

    <TextView
         />

    <TextView
         />

    <TextView
         />

    <EditText
        android:id="@+id/mobile"
        android:layout_width="wrap_content"
        android:layout_height="70dp"
        android:layout_below="@+id/regText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:clickable="true"
        android:focusable="true"
        android:hint="Enter Mobile Number"
        android:inputType="phone"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="15sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/regText" />

    <EditText
        android:id="@+id/pin_code"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_below="@+id/mobile"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:autofillHints="Enter Area Pin Code"
        android:clickable="true"
        android:focusable="true"
        android:hint="Enter Area Pin Code"
        android:inputType="number"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="15sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mobile" />

    <TextView
        android:id="@+id/verify_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/pin_code"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="Verify mobile number with OTP"
        android:textAlignment="center"
        android:textColor="#696969"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/pin_code" />

    <Button
        android:id="@+id/get_otp_button"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_below="@+id/verify_text"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:alpha="1"
        android:backgroundTint="#00FA9A"
        android:text="Get OTP"
        android:textAlignment="center"
        android:textColor="#696969"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/verify_text" />

    <EditText
        android:id="@+id/gen_otp"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_below="@+id/verify_text"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:alpha="0"
        android:clickable="true"
        android:focusable="true"
        android:hint="Enter OTP"
        android:inputType="number"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="15sp"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/verify_text" />

    <Button
        android:id="@+id/verify_otp_button"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_below="@+id/get_otp_button"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:alpha="0"
        android:backgroundTint="#00FA9A"
        android:text="Verify OTP"
        android:textAlignment="center"
        android:textColor="#696969"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/gen_otp" />

</androidx.constraintlayout.widget.ConstraintLayout> 

我遇到的问题是,当显示第三个 otp EditText 时,它不显示虚拟键盘或在单击时获得焦点。相反,我必须先单击前两个 EditText 之一才能显示虚拟键盘。

我怎样才能让虚拟键盘在一次单击 OTP 字段时显示? 这是 java 文件。

RegistrationActivity.java:

package com.example.covislot;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.firebase.FirebaseException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.TimeUnit;

public class RegistrationActivity extends AppCompatActivity {

    EditText mobileField, pinField,otpField;
    Button getOTP, verifyOTP;
    String mobileNumber, pinCode, OTP;

    PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallback;
    FirebaseAuth auth;
    private String verificationCode;

    SharedPreferences sp;

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

        sp =  getSharedPreferences("login",MODE_PRIVATE);

        StartFirebaseLogin();

        mobileField = findViewById(R.id.mobile);
        pinField = findViewById(R.id.pin_code);
        otpField = findViewById(R.id.gen_otp);

        getOTP = findViewById(R.id.get_otp_button);
        verifyOTP = findViewById(R.id.verify_otp_button);

        getOTP.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (TextUtils.isEmpty(mobileField.getText().toString())) {
                    // when mobile number field is empty
                    // displaying a toast message.
                    Toast.makeText(RegistrationActivity.this, "Please enter a valid phone number.", Toast.LENGTH_SHORT).show();
                } else {
                    mobileNumber = "+91" + mobileField.getText().toString();
                }
                if (TextUtils.isEmpty(pinField.getText().toString())) {
                    // when pin number field is empty
                    // displaying a toast message.
                    Toast.makeText(RegistrationActivity.this, "Please enter a valid Pin code.", Toast.LENGTH_SHORT).show();
                } else {
                    pinCode = pinField.getText().toString();
                }

                PhoneAuthOptions options =
                        PhoneAuthOptions.newBuilder(auth)
                                .setPhoneNumber(mobileNumber)       // Phone number to verify
                                .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
                                .setActivity(RegistrationActivity.this)                 // Activity (for callback binding)
                                .setCallbacks(mCallback)          // OnVerificationStateChangedCallbacks
                                .build();
                PhoneAuthProvider.verifyPhoneNumber(options);
            }
        });

        verifyOTP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(otpField.getText().toString())) {
                    // when otp field is empty
                    // displaying a toast message.
                    Toast.makeText(RegistrationActivity.this, "Please enter a valid OTP.", Toast.LENGTH_SHORT).show();
                } else {
                    OTP = otpField.getText().toString();
                }
                PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCode, OTP);
                SigninWithPhone(credential);
            }
         });
    }

    private void SigninWithPhone(PhoneAuthCredential credential) {
        auth.signInWithCredential(credential)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            sp.edit().putBoolean("logged", true).apply();
                            sp.edit().putString("phone", mobileNumber).apply();
                            sp.edit().putString("pinCode", pinCode).apply();
                            startActivity(new Intent(RegistrationActivity.this,SignedInActivity.class));
                            finish();
                        } else {
                            Toast.makeText(RegistrationActivity.this,"Incorrect OTP",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void StartFirebaseLogin() {

        auth = FirebaseAuth.getInstance();
        mCallback = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

            @Override
            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                Toast.makeText(RegistrationActivity.this,"verification completed",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                Toast.makeText(RegistrationActivity.this,"verification failed",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);
                verificationCode = s;
                Toast.makeText(RegistrationActivity.this,"Code sent",Toast.LENGTH_SHORT).show();
                getOTP.animate().alpha(0f).setDuration(500);
                otpField.setVisibility(View.VISIBLE);
                otpField.animate().alpha(1f).setDuration(500);
                verifyOTP.setVisibility(View.VISIBLE);
                verifyOTP.animate().alpha(1f).setDuration(600);
            }
        };
    }
}

当你想给它焦点时把这行:

otpField.requestFocus();

此外,要显式显示软键盘,您可以执行以下操作:

otpField.postDelayed(new Runnable() {
    @Override
    public void run() {
        InputMethodManager im = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        im.showSoftInput(otpField, InputMethodManager.SHOW_IMPLICIT);
    }
},200);