Android 监听软键盘显示和隐藏

Android 监听软键盘显示和隐藏

1、监听软键盘

由于官方没有提供相关的监听,只能通过界面布局来判断软键盘显示和隐藏。
(1) 通过OnLayoutChangeListener来监听
getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
		@Override
		public void onLayoutChange(View v, int left, int top, int right, int bottom,
					int oldLeft, int oldTop, int oldRight, int oldBottom) {
		}
	});
(2) 通过OnGlobalLayoutListener来监听
getWindow().getDecorView().getViewTreeObserver()
		.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
				@Override
				public void onGlobalLayout() {
				}
			});
	}
(3) 判断软键盘显示和隐藏。
private boolean isShowing() {
	//获取当前屏幕内容的高度
	int screenHeight = getWindow().getDecorView().getHeight();
	
	//获取View可见区域的bottom
	Rect rect = new Rect();
	getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);	

	return screenHeight > rect.bottom;
}

2、软键盘显示

软键盘显示时可能会覆盖某些控件,必要时需要移动界面。
private void onLayout() {
	int screenHeight = getWindow().getDecorView().getHeight();

	//获取View可见区域的bottom
	Rect rect = new Rect();
	getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

	if (screenHeight > rect.bottom) {
		// mTranslate用来记录是否已经移动
		if (!mTranslate) {
			// 获取按钮的左上角,按钮高度为40dp
			int[] location = new int[2];
			mBtn.getLocationOnScreen(location);
			int bottom = location[1] + getResources().getDimensionPixelSize(R.dimen.margin_xdpi_50);

			// 如果按钮被覆盖,移动整个界面向上移动
			if (bottom > rect.bottom) {
				getWindow().getDecorView().scrollBy(0, bottom - rect.bottom);
				mTranslate = true;
			}
		}
	} else {
		getWindow().getDecorView().scrollTo(0, 0);
		mTranslate = false;
	}

}
显示如下


参考资料:https://www.cnblogs.com/shelly-li/p/5639833.html
参考资料:http://blog.csdn.net/sinat_31311947/article/details/53914000


猜你喜欢

转载自blog.csdn.net/chennai1101/article/details/79398853
今日推荐