Skip to content

Instantly share code, notes, and snippets.

@kailash09dabhi
Created October 7, 2014 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kailash09dabhi/3ac4cbeb07be570ac244 to your computer and use it in GitHub Desktop.
Save kailash09dabhi/3ac4cbeb07be570ac244 to your computer and use it in GitHub Desktop.
KeyBoard Utility class for detecting keyboard appear disappear events and showing and hiding keyboard.
package com.upicit.utility;
import android.app.Activity;
import android.content.Context;
import android.inputmethodservice.KeyboardView;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import com.upicit.R;
import java.security.Key;
/**
* @author kailash09dabhi@gmail.com
*/
public class KeyboardUtil {
private KeyboardUtil() {
}
/**
* This function is used to hide the virtual keyboard.
*
* @param activity
*/
public static void hideKeyBoard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
.getWindowToken(), 0);
}
/**
* Shows the soft keyboard
*/
public static void showSoftKeyboard(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) view
.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
view.requestFocus();
inputMethodManager.showSoftInput(view, 0);
}
public interface OnKeyBoardAppearListener {
public void onKeyBoardAppear();
public void onKeyBoardDisappear();
}
/**
* This method works only when Activity is instance of ActionbarActivity and it has overlayed actionbar.
*
* @param activity
* @param onKeyBoardAppearListener
*/
public static void setKeyBoardAppearListener(final ActionBarActivity activity, final OnKeyBoardAppearListener onKeyBoardAppearListener) {
final View activityRootView = activity.findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView()
.getHeight() - activityRootView.getHeight() - activity.getSupportActionBar().getHeight();
if (heightDiff > 100) { // if more than 100 pixels, its
// probably a keyboard...
onKeyBoardAppearListener.onKeyBoardAppear();
} else {
onKeyBoardAppearListener.onKeyBoardDisappear();
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment