android 监听判断软键盘的弹出、隐藏状态

1、自定义View

public class ResizeLayout extends RelativeLayout {

	public static final byte KEYBOARD_STATE_SHOW = -3;
	public static final byte KEYBOARD_STATE_HIDE = -2;
	public static final byte KEYBOARD_STATE_INIT = -1;

	private boolean mHasInit = false;
	private boolean mHasKeyboard = false;
	private int mHeight;

	private IOnKeyboardStateChangedListener onKeyboardStateChangedListener;

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

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

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

	public void setOnKeyboardStateChangedListener(
			IOnKeyboardStateChangedListener onKeyboardStateChangedListener) {
		this.onKeyboardStateChangedListener = onKeyboardStateChangedListener;
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		if (!mHasInit) {
			mHasInit = true;
			mHeight = b;
			if (onKeyboardStateChangedListener != null) {
				onKeyboardStateChangedListener
						.onKeyboardStateChanged(KEYBOARD_STATE_INIT);
			}
		} else {
			mHeight = mHeight < b ? b : mHeight;
		}

		if (mHasInit && mHeight > b) {
			mHasKeyboard = true;
			if (onKeyboardStateChangedListener != null) {
				onKeyboardStateChangedListener
						.onKeyboardStateChanged(KEYBOARD_STATE_SHOW);
			}
		}
		if (mHasInit && mHasKeyboard && mHeight == b) {
			mHasKeyboard = false;
			if (onKeyboardStateChangedListener != null) {
				onKeyboardStateChangedListener
						.onKeyboardStateChanged(KEYBOARD_STATE_HIDE);
			}
		}
	}

	public interface IOnKeyboardStateChangedListener {
		public void onKeyboardStateChanged(int state);
	}
}


Activity中:

implements IOnKeyboardStateChangedListener

ResizeLayout resizeLayout;

resizeLayout.setOnKeyboardStateChangedListener(this);

 

@Override
	public void onKeyboardStateChanged(int state) {
		switch (state) {
		case ResizeLayout.KEYBOARD_STATE_HIDE:// 软键盘隐藏
			talkLayout.setVisibility(View.INVISIBLE);
			flGoKeyboard.setVisibility(View.VISIBLE);
			break;
		case ResizeLayout.KEYBOARD_STATE_SHOW:// 软键盘显示
			talkLayout.setVisibility(View.VISIBLE);
			flGoKeyboard.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
	}


 


2、直接使用系统的控件

relativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						int heightDiff = keyboardLay.getRootView().getHeight()
								- keyboardLay.getHeight();
						if (heightDiff > 100) { // 说明键盘是弹出状态

						} else {

						}
					}
				});


 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值