前不久一个朋友问了一个简单的问题,就是需要根据软键盘的显示与否控制一些view的显示。所以写了一个小demo,试了一下,效果还ok。现在贴出来,作个记录。
思想是重写RelativeLayout,根据其中onSizeChanged方法来进行判断软键盘是否显示。
下面是重写的relativeLayout内容:
public class SoftKeybroadRelativeLayout extends RelativeLayout {
private InputWindowListener listener;
public SoftKeybroadRelativeLayout(Context context, InputWindowListener listener) {
super(context);
this.listener = listener;
}
public SoftKeybroadRelativeLayout(Context context) {
super(context);
}
public SoftKeybroadRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SoftKeybroadRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (oldh > h) {
if (listener != null)
listener.show();
} else {
if (listener != null)
listener.hidden();
}
}
public void setListener(InputWindowListener listener) {
this.listener = listener;
}
}
主要的处理逻辑是在onSizeChanged方法里面。
* @param w Current width of this view.
* @param h Current height of this view.
* @param oldw Old width of this view.
* @param oldh Old height of this view.
所以进行比较高度就可以了。
下面是其中InputWindowListener
public interface InputWindowListener {
void show();
void hidden();
}
然后在需要处理的时候利用该SoftKeybroadRelativeLayout 代替RelativeLayout,设置Listener,在需要处理的Activity的清单配置文件中设置属性为:
android:windowSoftInputMode=”adjustResize”
tip:
android:windowSoftInputMode=”adjustResize” 该属性如果在全屏模式下会失效,导致软键盘的显示和隐藏也有问题。
这是一种简单的实现方式,因为他要做的activity并不是全屏,所以这里先TODO一下该问题,以后有机会再处理下 n(≧▽≦)n。