您的位置:首页 > 移动开发 > Android开发

android软键盘现实和隐藏的监听

2015-07-03 14:37 603 查看
http://stackoverflow.com/questions/4312319/howto-capture-the-virtual-keyboard-show-hide-event-in-android
http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android?lq=1
大概的方法就是监听view的的高度的变化,来判断软键盘的显示和隐藏。

注意:一点就是属性要设置的好,很多情况下试adjustResize才有效。

import java.util.Arraylist;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

public class KeyboardDetectorRelativeLayout extends RelativeLayout {

public interface IKeyboardChanged {
void onKeyboardShown();
void onKeyboardHidden();
}

private ArrayList<IKeyboardChanged> keyboardListener = new ArrayList<IKeyboardChanged>();

public KeyboardDetectorRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public KeyboardDetectorRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

public KeyboardDetectorRelativeLayout(Context context) {
super(context);
}

public void addKeyboardStateChangedListener(IKeyboardChanged listener) {
keyboardListener.add(listener);
}

public void removeKeyboardStateChangedListener(IKeyboardChanged listener) {
keyboardListener.remove(listener);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
final int actualHeight = getHeight();

if (actualHeight > proposedheight) {
notifyKeyboardShown();
} else if (actualHeight < proposedheight) {
notifyKeyboardHidden();
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

private void notifyKeyboardHidden() {
for (IKeyboardChanged listener : keyboardListener) {
listener.onKeyboardHidden();
}
}

private void notifyKeyboardShown() {
for (IKeyboardChanged listener : keyboardListener) {
listener.onKeyboardShown();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: