1、EditText中添加**android:imeOptions=”actionSearch”
android:singleLine=”true”**两行,注意:不能使用AS推荐使用的maxLines=“1”,否则不会弹出搜索键
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<EditText
android:id="@+id/search_member_et"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffffff"
android:hint="搜索"
**android:imeOptions="actionSearch"
android:singleLine="true"**
android:paddingLeft="12dp"
android:textColor="@color/colorPrimaryDark"
android:textColorHint="#000000"
android:textSize="14sp" />
</LinearLayout>
2、java代码中添加事件监听:
mSearchMemberEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH && mSearchMemberEt.getText().length() != 0) {
//这里我是控制的一定要输入字才执行搜索
//《---------点击搜索后要做的事--------》
return true;
}
return false;
}
});
3、其他:系统输入法为谷歌输入法时有可能出现输入数字不显示的问题(亲测摩托罗拉手机上出现了),强制监听按下的数字键并且设置到EditText的text中去。
mSearchEt.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_0://安卓系统定义的数值:7
case KeyEvent.KEYCODE_1://8
case KeyEvent.KEYCODE_2://9
case KeyEvent.KEYCODE_3://10
case KeyEvent.KEYCODE_4://11
case KeyEvent.KEYCODE_5://12
case KeyEvent.KEYCODE_6://13
case KeyEvent.KEYCODE_7://14
case KeyEvent.KEYCODE_8://15
case KeyEvent.KEYCODE_9://16
String text = mSearchEt.getText().toString();
text += keyCode - 7;
mSearchEt.setText(text);
mSearchEt.setSelection(text.length());
break;
}
}
return true;
}});