您的位置:首页 > 移动开发 > Android开发

Android中检测软键盘的弹出和关闭

2013-07-03 20:34 127 查看
Android系统并没有提供明显的API来监听软键盘的弹出和关闭,但是在某些情况下我们还是有办法来检测软键盘的弹出和关闭。

从StackOverflow找到了一个不错的方法。但是这种只适用于在manifest中目标Activity设置android:windowSoftInputMode=”adjustResize”的情况。

adjustResize表示The activity’s main window is always resized to make room for the soft keyboard on screen.

然后我们需要设置Activity的根视图的id,用来判断对话框弹出关闭使用。

布局的示例代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/root_layout"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"

/>

</RelativeLayout>


判断对话框出现或者关闭的逻辑代码如下:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View activityRootView = findViewById(R.id.root_layout);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
private int preHeight = 0;
@Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
System.out.println("height differ = " + heightDiff);
//在数据相同时,减少发送重复消息。因为实际上在输入法出现时会多次调用这个onGlobalLayout方法。
if (preHeight == heightDiff) {
return;
}
preHeight = heightDiff;
if (heightDiff > 100 ) {
//		        	System.out.println("input method shown!");
Toast.makeText(getApplicationContext(), "keyboard is  shown", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "keyboard is hidden ", Toast.LENGTH_SHORT).show();
}
}

});
}


give your activity’s root view a known ID, say ‘@+id/activityRoot’, hook a GlobalLayoutListener into the ViewTreeObserver,
and from there calculate the size diff between your activity’s view root and the window size

给你的Activity的根视图设置一个id,比如说”@+id/activityRoot”,在ViewTreeObserver上设置一个GlobalLayoutListener。然后计算你的Activity的根视图和Window尺寸的差值
如果插值大于 100 (这是一个相对比较合理的值),就认为是对话框弹出,否则为对话框隐藏。

相关链接:http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: