简体   繁体   中英

How to clear focus from edittext when the keyboard closes after click back button?

I have an AppBarLayout and I hide when I touch EditText .

SearchFragment.class

 binding.searchEt.setOnFocusChangeListener { view, hasFocus ->
        if (hasFocus) {
            binding.appBarLayout.setExpanded(false, true)
        } else {
            binding.appBarLayout.setExpanded(true, true)
        }
    }

But I can't show again AppBarLayout when keyboard closes. Because when keyboard closes EditText focus does not change.

Xml

 <EditText
     android:id="@+id/searchEt"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_centerVertical="true"
     android:layout_marginStart="8dp"
     android:layout_toStartOf="@+id/close_button"
     android:layout_toEndOf="@+id/ic_search"
     android:background="@android:color/transparent"
     android:focusable="true"
     android:focusableInTouchMode="true"
     android:fontFamily="@font/catamaran_bold"
     android:hint="@string/search_hint"
     android:imeOptions="actionSearch"
     android:includeFontPadding="true"
     android:orientation="vertical"
     android:paddingStart="12dp"
     android:singleLine="true"
     android:textAlignment="viewStart"
     android:textColor="#000"
     android:textDirection="locale"
     android:textSize="18dp"
     tools:text="alskjfdn" />

How can I clear focus when keyboard hide? Cursor still showing after keyboard hidden.

use something like this:

public void hideKeyboard(Activity activity){
  InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
  View view = activity.getCurrentFocus();
  if(view != null){
    view.clearFocus();
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
  }
}

inside the keyboard close listener, after close keyboard clear focus from editText

editText.setFocusable(false);
editText.setFocusableInTouchMode(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM