[Android] EditText:アクションボタンの動作を指定する

EditTextはテキスト入力時に表示されるキーボードの種類を指定できることに加えて、アクションボタン押下時の動作を指定することもできます。ここでは、キーボードのアクションボタンの動作を指定する方法について説明します。
広 告
目次
前提条件
動作確認端末
1. アクションボタンのアイコンを変更する
<EditText>
タグのandroid:imeOptions属性を設定することによって、キーボードのアクションボタンのアイコンが変わり、アクションを指定することが出来ます。Android:imeOptions属性を使ったコードは以下のようになります。
android:imeOptions属性を使ったサンプルコード
<EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:imeOptions="actionSend" />
JavaコードからはsetImeOptions (int imeOptions)を使用します。引数にはEditorInfoクラスに定義されているアクションIDの定数(IME_ACTION_XXX)を指定します。
setImeOptions (int imeOptions)を利用したサンプルコード
final EditText editText = (EditText) findViewById(R.id.editText); editText.setImeOptions(EditorInfo.IME_ACTION_SEND);
実行すると以下のようにアクションが送信用アイコンに変化します。

android:imeOptoins=”actionSearch”
と指定すると、アクションボタンが検索用のものに変化します。

android:imeOptoins
属性で設定できる値とsetImeOptions (int imeOptions)
の引数についての詳しい情報は公式ドキュメント参照して下さい。
2. アクションボタンイベントを受け取る
android:imeOptions
やsetImeOptions (int imeOptions)
でアクションが指定された場合、TextView#OnEditorActionListenerを使ってイベントリスナーを登録できます。TextView#OnEditorActionListener
にはonEditorAction (TextView v, int actionId, KeyEvent event)というコールバックメソッドがあり、引数としてアクションID(IME_ACTION_XXX)が渡されます。
TextView#OnEditorActionListenerを使ったサンプルコード
final EditText editText = (EditText) findViewById(R.id.editText); editText.setOnEditorActionListener(new TextView.OnEditorActionListener(){ @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEND) { // メッセージ送信等の処理を記述 return true; } return false; } });
3. アクションボタンに任意のラベルを設定する
android:imeActionLabel属性を使用することでアクションボタンを任意の文字を設定することが出来ます。
Note : この設定が反映されるのは「Googleキーボード」のみです。

android:imeActionLabel属性を使ったサンプルコード
<!-- @string/launcheの実体は「起動」 --> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:imeActionLabel="@string/launch" />
JavaコードからはsetImeActionLabel (CharSequence label, int actionId)を使用します。
setImeActionLabel (CharSequence label, int actionId)w使ったサンプルコード
// @string/launchの実体は「起動」 final EditText editText = (EditText) findViewById(R.id.editText); editText.setImeActionLabel(getString(R.string.launch), 100);
実行すると以下のようにアクションボタン部分が設定した文字になっています。
