Skip to content

Instantly share code, notes, and snippets.

@Kishanjvaghela
Last active August 11, 2016 07:23
Show Gist options
  • Save Kishanjvaghela/95019e6bd9194b63e131137a3c50577f to your computer and use it in GitHub Desktop.
Save Kishanjvaghela/95019e6bd9194b63e131137a3c50577f to your computer and use it in GitHub Desktop.
public class BaseActivity extends Activity implements DetectsSoftKeyboardLayout.OnSoftKeyboardListener
{
DetectsSoftKeyboardLayout rootlayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootLayout.setOnSoftKeyboardListener(this);
}
@Override
public void onShown() {
Log.d(TAG, "onShown: ");
// keyboard visible
}
@Override
public void onHidden() {
Log.d(TAG, "onHidden: ");
// keyboard hidden
}
}
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RelativeLayout;
public class DetectsSoftKeyboardLayout extends RelativeLayout {
private static final String TAG = "DetectsSoftKeyboardLayo";
public DetectsSoftKeyboardLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DetectsSoftKeyboardLayout(Context context) {
super(context);
}
private OnSoftKeyboardListener onSoftKeyboardListener;
@Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
if (onSoftKeyboardListener != null) {
final int newSpec = MeasureSpec.getSize(heightMeasureSpec);
final int oldSpec = getMeasuredHeight();
if (oldSpec == 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
Log.d(TAG, "onMeasure: new " + newSpec);
Log.d(TAG, "onMeasure: old " + oldSpec);
int diff = newSpec - oldSpec;
if (Math.abs(diff) < 200) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
if (diff < 0) {
Log.d(TAG, "onMeasure: shown");
onSoftKeyboardListener.onShown();
} else if (diff > 0) {
Log.d(TAG, "onMeasure: hidden");
onSoftKeyboardListener.onHidden();
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public final void setOnSoftKeyboardListener(final OnSoftKeyboardListener listener) {
this.onSoftKeyboardListener = listener;
}
public interface OnSoftKeyboardListener {
void onShown();
void onHidden();
}
}
<mywidget.DetectsSoftKeyboardLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/baseRootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- your layout -->
</mywidget.DetectsSoftKeyboardLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment