2010-07-18 75 views
48

我有一個編輯文本,定義如下。Android:編輯文本開始按鈕

<EditText 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:maxLines="1" 
android:inputType="text" 
android:hint="@string/field_text" 
android:id="@+id/field" 
/> 

我想,這樣當有人點擊該完成/啓動按鈕在屏幕鍵盤上點擊一個按鈕來設置自定義命令或只是運行由該按鈕運行方法。我認爲這與ime選項有關,但我一直無法弄清楚它們是如何工作的。預先感謝任何幫助!

回答

117

您想使用Android的組合:相應imeOptions和setOnEditorActionListener

<EditText android:id="@+id/some_edittext" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:imeOptions="actionSend"> 
</EditText> 


some_edittext.setOnEditorActionListener(new OnEditorActionListener() { 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
     if (actionId == EditorInfo.IME_ACTION_SEND) { 
      some_button.performClick(); 
      return true; 
     } 
     return false; 
    } 
}); 

很顯然,你應該改變actionSend你想要的動作,並更新IME_ACTION_SEND。

+1

只是想跟進這個答案,並提到這並不一定適用於所有設備。例如,我將我的OnKeyListener代碼更改爲在我的應用程序中使用OnEditorActionListener,突然我的HTC Evo停止執行該操作。看到這個更多的信息:http://stackoverflow.com/questions/3886677/imeoptions-on-htc-devices – Dan 2011-05-13 20:32:31

+0

很好的例子.... – AndroidDanger 2011-06-08 07:03:33

+0

但使用這個例子,你不能創建多行editext.Like聊天文本,在這個你添加的文本不是Wrodwrap automaticaly。 – 2014-01-01 04:50:03