开发背景:Android 电子白板,需要实现输入法跟随输入功能
- 首先要确定输入法绑定的输入框坐标,因为输入法的启动是通过
InputMethodManager#startInputInner
方法,所以我们在InputMethodManager#startInputInner
方法中,用SystemProperties将View的坐标保存:
InputMethodManager.java
import android.os.SystemProperties;
boolean startInputInner(@InputMethodClient.StartInputReason final int startInputReason,
IBinder windowGainingFocus, int controlFlags, int softInputMode,
int windowFlags) {
...
int locationInScreen[] = new int[2];
view.getLocationOnScreen(locationInScreen);
SystemProperties.set("viewPositionInScreen",locationInScreen[0]+"_"+locationInScreen[1]);
}
- 最后,在输入法代码中设置键盘需要显示的位置:
int [] viewPositionXY=SystemProperties.get("viewPositionInScreen","0_0").split("_");
//下面是自定义键盘的InputMethodService类设置键盘位置的伪代码 WindowManager.LayoutParams lp = getWindow().getWindow().getAttributes();
lp.x = viewPositionXY[0] - screenWidth/2;//由于键盘是底部居中,屏幕中间右侧为正x,左侧为负x,screenWidth为屏幕的宽
lp.y = viewPositionXY[1] - keybaordHeight;//keybaordHeight为键盘的高度
输入法启动的详细流程:Android InputMethod 源码分析,显示输入法流程_JieQiong1的博客-CSDN博客_android 输入法源码