Created
June 15, 2016 06:12
-
-
Save surajsau/32f9b8231fe2e66bef7b8574b46af0d0 to your computer and use it in GitHub Desktop.
LinearLayout which identifies whether soft keyboard is visible or hidden
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity; | |
import android.content.Context; | |
import android.graphics.Rect; | |
import android.util.AttributeSet; | |
import android.widget.LinearLayout; | |
/** | |
* Created by suraj on 15/6/2016. | |
* | |
* This linear layout is used to listen to visibility of the soft keyboard. | |
* In the onMeasure, based on the height difference between the original rootView and | |
* the current rootView, it decides whether keyboard is open or not. | |
* | |
* This boolean is then sent as a callback to the KeyboardVisibilityListener. | |
* | |
* The current height difference threshold is kept as 128. | |
* | |
*/ | |
public class DetectSoftKeyboardLinearLayout extends LinearLayout { | |
public DetectSoftKeyboardLinearLayout(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public interface KeyboardVisibilityListener { | |
void onKeyBoardVisibilityChanged(boolean isVisible); | |
} | |
private KeyboardVisibilityListener mListener; | |
public void addKeyboardVisibilityListener(KeyboardVisibilityListener listener) { | |
mListener = listener; | |
} | |
@Override | |
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
int height = MeasureSpec.getSize(heightMeasureSpec); | |
Activity activity = (Activity)getContext(); | |
Rect rect = new Rect(); | |
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); | |
int statusBarHeight = rect.top; | |
int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight(); | |
int diff = (screenHeight - statusBarHeight) - height; | |
if (mListener != null) { | |
mListener.onKeyBoardVisibilityChanged(diff>128); // assume all soft keyboards are at least 128 pixels high | |
} | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
} | |
public boolean isKeyboardVisibilityListenerAdded() { | |
return mListener != null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment