Reputation: 1691
I have a RecyclerView
and below there's an EditText
. I want when user taps outside the EditText
to close the keyboard.
I searched and find this answer here but it doesn't work for me. User taps outside but EditText
still has focus.
My XML code is :
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_chatroom_messages_list"
android:paddingBottom="@dimen/spacing_medium"
android:layout_weight="1"
android:clickable="true" android:focusableInTouchMode="true" android:focusable="true"
android:layout_width="match_parent" android:layout_height="0dp"/>
<LinearLayout
android:orientation="horizontal"
android:background="@color/white"
android:layout_marginLeft="@dimen/spacing_large" android:layout_marginBottom="@dimen/spacing_medium"
android:layout_marginRight="@dimen/spacing_large" android:paddingRight="@dimen/spacing_medium"
android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText
android:id="@+id/et_chatroom_send_message"
android:layout_gravity="bottom"
android:background="@null"
android:textSize="@dimen/app_text_size_normal" android:hint="Type to reply"
android:layout_marginLeft="@dimen/spacing_large" android:layout_marginRight="@dimen/spacing_large"
android:layout_weight="1"
android:layout_width="0dp" android:layout_height="@dimen/spacing_xlarge" android:inputType="textMultiLine" />
<ImageView
android:id="@+id/iv_chatroom_send_message_btn"
android:src="@drawable/ic_pong_2"
android:layout_gravity="center"
android:layout_width="48dp" android:layout_height="48dp" android:contentDescription="Send msg button" />
</LinearLayout>
Upvotes: 1
Views: 2817
Reputation: 756
Call this method on recyclerview touch listener...
public static void hideKeyboard(final Activity activity) {
final View view = activity.getCurrentFocus();
final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (view == null) {
View view2 = new View(activity);
imm.hideSoftInputFromWindow(view2.getWindowToken(), 0);
} else {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}, 125);
}
Upvotes: 1
Reputation: 1077
Simply set an onTouchListener()
to your RecyclerView
and call the hideKeyboard()
method from it.
Upvotes: 2
Reputation: 4891
close it when your editText
losses it's focus.
like that:
EditText editText = (EditText) findViewById(R.id.edittxt);
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
});
Upvotes: 1