2010年12月30日木曜日

Android ダイアログ表示時にソフトキーボードを出す

この方法は別にダイアログ(Dialog)でなくても、どこでも使えます。

showSoftInput メソッドを使います。

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); を使う方法は gabu さんのブログ EditTextを持つダイアログ(AlertDialog)が表示された時に自動的にソフトキーボードを表示する。 - gabuchanの日記 - にのっています。


以前のエントリでボタンを押したときにソフトキーボードを表示する方法を紹介しました。

Y.A.M の 雑記帳: Android ボタンを押したときにソフトキーボードを消す

このときと同様に InputMethodManager を使います。

showSoftInput メソッドの第1引数で指定する View は EditView などの Editable な View にしてください(たぶん)。
# ちなみに、Button を第1引数に指定したらソフトキーボードは表示されません
# でした。リファレンスに "Explicitly request that the current input method's
# soft input area be shown to the user, if needed."
# とあるので、入力が必要な View を渡されたときだけ表示するんでしょうね。


  1. EditText editText = (EditText)findViewById(R.id.edittext);  
  2.   
  3. InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
  4. inputMethodManager.showSoftInput(editText, 0);  


ダイアログが表示されたときに自動でソフトキーボードをだすには、Dialog の onShow() で上記のコードを実行します。onFocusChange() で実行しても表示されません!

  1. final Dialog newDialog = new Dialog(this);  
  2. newDialog.setContentView(R.layout.mydialog);  
  3. newDialog.setOnShowListener(new DialogInterface.OnShowListener() {  
  4.     @Override  
  5.     public void onShow(DialogInterface arg0) {  
  6.         EditText editText = (EditText)newDialog.findViewById(R.id.edittext);  
  7.   
  8.         InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
  9.         inputMethodManager.showSoftInput(editText, 0);  
  10.     }  
  11. });  
  12. newDialog.show();  


res/layout/mydialog.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:orientation="vertical"  
  4.     android:layout_width="wrap_content"  
  5.     android:layout_height="wrap_content"  
  6.     android:padding="30dip"  
  7.     >  
  8.     <EditText  
  9.         android:id="@+id/edittext"  
  10.         android:layout_width="200dip"  
  11.         android:layout_height="wrap_content"  
  12.         android:inputType="text"  
  13.         />  
  14. </LinearLayout>  



# InputMethodManager には showSoftInputFromInputMethod() というメソッドもあるのですが、この人を実行してもなぜか
  1. W/InputManagerService(  109): Ignoring showMySoftInput of uid 10052 token: android.os.BinderProxy@4091e980  

# とかいわれて表示されませんでした。うむむ。


 

0 件のコメント:

コメントを投稿