2010-07-08 70 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 
} 
相关问题