2010-07-08 81 views
301

我無法弄清楚這一點。有些應用程序有一個EditText(文本框),當您觸摸它時,它會顯示屏幕鍵盤,鍵盤上有一個「搜索」按鈕,而不是輸入鍵。Android:如何讓鍵盤輸入按鈕說「搜索」並處理它的點擊?

我想實現這一點。我怎樣才能實現該搜索按鈕並檢測搜索按鈕的按下?

編輯:找到了如何實現搜索按鈕;在XML中,android:imeOptions="actionSearch"或Java,EditTextSample.setImeOptions(EditorInfo.IME_ACTION_SEARCH);。但我如何處理用戶按下該搜索按鈕?它與有什麼關係?

+2

請注意,imeOptions可能無法在某些設備上工作。請參閱[this](http://stackoverflow.com/questions/4470018/alternative-of-action-done-button-in-htc-desire)和[this](http://stackoverflow.com/questions/3886677/ imeoptions-ON-HTC-設備)。 – Ermolai 2013-03-15 08:31:20

回答

745

在佈局中設置要搜索的輸入法選項。

<EditText 
    android:imeOptions="actionSearch" 
    android:inputType="text" /> 

在java中添加編輯器動作偵聽器。

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { 
    @Override 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
     if (actionId == EditorInfo.IME_ACTION_SEARCH) { 
      performSearch(); 
      return true; 
     } 
     return false; 
    } 
}); 
+0

如果我們想要得到用戶點擊的鍵,比如a,b,c,該怎麼辦? – ozmank 2011-11-15 13:36:13

+72

在操作系統2.3.6上,直到我把android:inputType =「text」屬性,它才工作。 – thanhbinh84 2011-12-30 15:03:21

+0

不應該都是那些TextView的EditText表示嗎? – Carol 2012-03-02 21:01:21

3

xml文件,把imeOptions="actionSearch"inputType="text"maxLines="1"

當用戶點擊搜索
<EditText 
    android:id="@+id/search_box" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/search" 
    android:imeOptions="actionSearch" 
    android:inputType="text" 
    android:maxLines="1" /> 
5

隱藏鍵盤。除了Robby Pond回答

private void performSearch() { 
    editText.clearFocus(); 
    InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
    in.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0); 
    ...perform search 
} 
相關問題