1. 程式人生 > >Android軟鍵盤之程式碼改變軟鍵盤狀態

Android軟鍵盤之程式碼改變軟鍵盤狀態

Android中軟鍵盤的管理主要是通過InputMethodManager來完成的,

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

使用方法:
import android.app.Activity;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by Administrator on 2017/4/4.
 * 軟鍵盤工具類
 */

public class KeyboardUtil {

    /**
     * 顯示軟鍵盤,當佈局載入完成後呼叫,否則無效
     * @param context
     * @param focusView:必須為EditText或者其子類並且獲得焦點,並且是VISIBLE
     */
    public static void showSoftInput(Context context, EditText focusView){
        InputMethodManager inputMethodManager= (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            focusView.requestFocus();
            inputMethodManager.showSoftInput(focusView,0);
        }
    }

    /**
     * 隱藏軟鍵盤,當佈局載入完成後呼叫,否則無效
     * @param context
     */
    public static void hideSoftInput(Context context){
        InputMethodManager inputMethodManager= (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(((Activity)context).getWindow().getDecorView().getWindowToken(),0);
        }
    }

    /**
     * 切換軟鍵盤狀態(隱藏-顯示或顯示-隱藏),當佈局載入完成後呼叫,否則無效
     * @param context
     */
    public static void toggleSoftInput(Context context){
        InputMethodManager inputMethodManager= (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.toggleSoftInput(0,0);
        }
    }
}

參考部落格:Android手動顯示和隱藏軟鍵盤