サンプルコード
「InputMethodManager」の「showSoftInput()」を使えば、「ソフトウェアキーボード(SoftInput)」は表示される。
いつも「InputMethodManager」のAPIであることを忘れてしまうし、引数「int flags」に何を設定すればいいのか忘れてしまうので、以下のようにしている。
/**
* Soft input area be shown to the user.
*
* @param context The context to use
* @param view The currently focused view, which would like to receive soft keyboard input
* @return Result
*/
public static boolean showSoftInput(Context context, View view) {
return showSoftInput(context, view, 0);
}
/**
* Soft input area be shown to the user.
*
* @param context The context to use
* @param view The currently focused view, which would like to receive soft keyboard input
* @param flags Provides additional operating flags
* @return Result
*/
public static boolean showSoftInput(Context context, View view, int flags) {
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (null == imm) {
return false;
}
return imm.showSoftInput(view, flags);
}
前者を使うようにして、引数「int flags」のことは一切考えない。
基本的に、この考えでいいはずだ。
リファレンスの記載はこうなっている。
flags int: Provides additional operating flags. Currently may be 0 or have the SHOW_IMPLICIT bit set.
フラグには「0」か「SHOW_IMPLICIT」を設定できるのだが、
Flag for showSoftInput(View, int) to indicate that this is an implicit request to show the input window, not as the result of a direct request by the user. The window may not be shown in this case.
「SHOW_IMPLICIT」はユーザの明示的な要求ではなく、暗黙的な要求を示すということなので、主にシステムが使うのだと思う。
(※「minSdkVersion 21:Lollipop」を前提としたサンプルコード)
サンプルコード(おまけ)
この記事、
【Android】「EditTextを複数配置した画面」を起動時に「特定のEditText」にフォーカスを設定する方法
で書いたのだが、「ソフトウェアキーボード(SoftInput)」はそもそも、対象のViewにフォーカスが当たっていないと表示できない。
なので、おまけで、以下のようなのを考えてみた。
/**
* Soft input area be shown to the user.
*
* @param context The context to use
* @param view The currently focused view, which would like to receive soft keyboard input
* @param flags Provides additional operating flags
* @return Result
*/
public static boolean showSoftInput(Context context, View view, int flags) {
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (null == imm) {
return false;
}
boolean show = imm.showSoftInput(view, flags);
if (!show) {
view.setFocusable(true);
view.setFocusableInTouchMode(true);
boolean focus = view.requestFocus();
if (focus) {
return showSoftInput(context, view, flags);
}
}
return show;
}
「showSoftInput()」が失敗して表示できなかったとき、その原因である「フォーカスが当たっていない」を、一度だけ解決してみる実装だ。
但し、懸念がある。
発生し得るのか定かではないが、フォーカスが当たっているのに表示できない場合は、無限ループになる。
ちょっと怖いか?
リファレンスの記載はこうなので、
explicitly request that the current input method's soft input area be shown to the user, if needed.
「if needed」ではない場合というのは、表示されないというのは、普通にあるのかもしれない。
(※「minSdkVersion 21:Lollipop」を前提としたサンプルコード)