对于Android键盘事件Google并没有提供一个好的接口去监听它,有时候就为项目需要就必须要自己去想办法去监听,由于我最近也要实现登陆与注册的功能,我的想法很简单实现起来也比较容易,主要的原理是在将Activity的配置android:windowSoftInputMode设置成adjust_resize当然设成其它我觉得也是可以的只是这还没有测试,这样在键盘弹出时Android会将而已进行调整,直接上代码呢。
设置inputMode
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="adjustResize"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
设置监听而已变化
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //android.R.id.content 这是包含布局的父控件ID
View contentView = findViewById(android.R.id.content);
//设置而已监听器
contentView.addOnLayoutChangeListener(this);
}
根据值的变化判断键盘是否显示。
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
if(bottom < oldBottom){
onKeyboardState(true);
}else if(bottom > oldBottom){
onKeyboardState(false);
}
}
这样基本上就可以实现键盘的监听呢,我这样写基本上可以满足大部分需求。