Android中檢測軟鍵盤的彈出和關閉

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章