在开发中很多时候我们需要监听软键盘的状态,但是安卓又没有给我们这样的接口,怎么办呢?
我们可以把页面的跟布局设置为scroll或者界面设置为权重占满,这时当键盘弹起时会挤压屏幕,屏幕的高度就会发生变化,我们可以通过此变化来监听键盘的弹起和关闭,以下是代码和图
我的项目需求是键盘弹起时,把一个隐藏的布局显示,关闭时把此布局隐藏,贴图如下:
以下是具体实现的代码:
public class MainActivity extends Activity implements OnLayoutChangeListener{
//Activity最外层的Layout视图
private View activityRootView;
//屏幕高度
private int screenHeight = 0;
//软件盘弹起后所占高度阀值
private int keyHeight = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activityRootView = findViewById(R.id.root_layout);
//获取屏幕高度
screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
//阀值设置为屏幕高度的1/3
keyHeight = screenHeight/3;
}
@Override
protected void onResume() {
super.onResume();
//添加layout大小改变监听器
activityRootView.addOnLayoutChangeListener(this);
}
@Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//old是改变前的左上右下坐标点值,没有old的是改变后的左上右下坐标点值
//现在认为只要控件将Activity向上推的高度超过了1/3屏幕高,就认为软键盘弹起
if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){
Toast.makeText(MainActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();
}else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){
Toast.makeText(MainActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();
}
}
1万+

被折叠的 条评论
为什么被折叠?



