Skip to content

Instantly share code, notes, and snippets.

@gnumilanix
Created February 28, 2017 04:57
Show Gist options
  • Save gnumilanix/da4bb5385aebcc51b35b597de8e482b7 to your computer and use it in GitHub Desktop.
Save gnumilanix/da4bb5385aebcc51b35b597de8e482b7 to your computer and use it in GitHub Desktop.
Implementation of RecyclerView that will dismiss keyboard when scrolling.
package com.lalamove.core.view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.inputmethod.InputMethodManager;
/**
* Implementation of {@link RecyclerView} that will dismiss keyboard when scrolling.
*
* @author milan
*/
public class KeyboardDismissingRecyclerView extends RecyclerView {
private RecyclerView.OnScrollListener onKeyboardDismissingScrollListener;
private InputMethodManager inputMethodManager;
public KeyboardDismissingRecyclerView(Context context) {
this(context, null);
}
public KeyboardDismissingRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, -1);
}
public KeyboardDismissingRecyclerView(final Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setOnKeyboardDismissingListener();
}
/**
* Creates {@link OnScrollListener} that will dismiss keyboard when scrolling if the keyboard
* has not been dismissed internally before
*/
private void setOnKeyboardDismissingListener() {
onKeyboardDismissingScrollListener = new RecyclerView.OnScrollListener() {
boolean isKeyboardDismissedByScroll;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int state) {
switch (state) {
case RecyclerView.SCROLL_STATE_DRAGGING:
if (!isKeyboardDismissedByScroll) {
hideKeyboard();
isKeyboardDismissedByScroll = !isKeyboardDismissedByScroll;
}
break;
case RecyclerView.SCROLL_STATE_IDLE:
isKeyboardDismissedByScroll = false;
break;
}
}
};
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
addOnScrollListener(onKeyboardDismissingScrollListener);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
removeOnScrollListener(onKeyboardDismissingScrollListener);
}
/**
* Hides the keyboard
*/
public void hideKeyboard() {
getInputMethodManager().hideSoftInputFromWindow(getWindowToken(), 0);
clearFocus();
}
/**
* Returns an {@link InputMethodManager}
*
* @return input method manager
*/
public InputMethodManager getInputMethodManager() {
if (null == inputMethodManager) {
inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
}
return inputMethodManager;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment