Android 7.0 使用自定义键盘弹出的位置有问题解决方式

本文介绍了一个在Android 7.0设备上出现的自定义键盘位置偏移问题及其解决方案。通过检查Android版本并调整键盘显示位置,确保了键盘在不同Android版本上的正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本来使用自定义键盘,使用popuwindow来弹出界面,在7.0以前的手机上好,有一天测试人员说在android 7.0的手机上,键盘的位置会跑掉,赶紧搜了一下,发现很多人遇到这个问题,应该是谷歌自身的bug,解决的方式就是检查如果是7.0的手机的话,就使用决定定位,如下代码:

mKeyboardView.setKeyboard(mKeyboard);
				mKeyboardWindow.setAnimationStyle(R.style.AnimBottom);

				if (Build.VERSION.SDK_INT < 24) {
					mKeyboardWindow.showAtLocation(this.mDecorView, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
				} else {
					// 适配 android 7.0  
					int[] location = new int[2];
					getLocationOnScreen(location);
					int x = location[0];
					int y = location[1];

					mKeyboardWindow.showAtLocation(mDecorView, Gravity.TOP, 0,
							DensityDpToPx.dpToPx(context, CommDataUtil.getAndroiodScreenProperty(context)));

				}

其中DensityDpToPx.dpToPx方法,和CommDataUtil.getAndroiodScreenProperty方法的代码如下:

/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dpToPx(final Context context, final float dp) {
		return (int) (dp * context.getResources().getDisplayMetrics().density);
	}
public static int getAndroiodScreenProperty(Context context) {//获取屏幕高度
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics dm = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels; // 屏幕宽度(像素)
		int height = dm.heightPixels; // 屏幕高度(像素)
		float density = dm.density; // 屏幕密度(0.75 / 1.0 / 1.5)
		int densityDpi = dm.densityDpi; // 屏幕密度dpi(120 / 160 / 240)
		// 屏幕宽度算法:屏幕宽度(像素)/屏幕密度
		int screenWidth = (int) (width / density); // 屏幕宽度(dp)
		int screenHeight = (int) (height / density);// 屏幕高度(dp)
		return screenHeight;
	}
其中关键是这个:mKeyboardWindow.showAtLocation(mDecorView, Gravity.TOP, 0,
DensityDpToPx.dpToPx(context, CommDataUtil.getAndroiodScreenProperty(context)));//设置键盘从底部弹出来

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值