A recent development on the chat interface involves EditText’s focus gain and loss to control the display and hiding of relevant parts of the page and the virtual keyboard. Every time I meet such demand, I have to go to Google or Baidu, and often spend time but do not get a satisfactory answer.

Step 1: When we enter the page, we default the focus to the parent of the EditText container

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:gravity="center">

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:background="# 00000000"
        android:hint="input you content"
        android:textColor="#1E1F28"
        android:textColorHint="#ACAEC4"
        android:textSize="14sp" />
</LinearLayout>Copy the code

The purpose of this operation is not to pop up the virtual keyboard when entering the page, but also to meet our needs

Step 2: We need EditText to listen for OnFocusChangeListener

contentEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus) {// Get focus}else{// Lose focus}}});Copy the code

When we click on the EditText input box we call OnFocusChangeListener’s onFocusChange method, hasFocus returns true, and we usually pop up the virtual keyboard

If you listen to EditText to get focus, how do you lose focus?

Take it one step at a time…

Finally: Lose focus

contentEdit.cleanFocus();Copy the code

After losing focus, the onFocusChange method in step 2 returns hasFocus as false, where we can manipulate the virtual keyboard hide.

Note: Without the contentedit.cleanFocus () method, onFocusChange is called only after the first focus and not later, which is often overlooked and often not enough for our purposes