软键盘的Enter键默认显示的是“完成”文本,我们知道按Enter建表示前置工作已经准备完毕了,要去什么什么啦。比如,在一个搜索中,我们输入要搜索的文本,然后按Enter表示要去搜索了,但是默认的Enter键显示的是“完成”文本,看着不太合适,不符合搜索的语义,如果能显示“搜索”两个字或者显示一个表示搜索的图标多好。事实证明我们的想法是合理的,Android也为我们提供的这样的功能。通过设置android:imeOptions来改变默认的“完成”文本。这里举几个常用的常量值:
- actionUnspecified 未指定,对应常量EditorInfo.IME_ACTION_UNSPECIFIED.效果:
- actionNone 没有动作,对应常量EditorInfo.IME_ACTION_NONE 效果:
- actionGo 去往,对应常量EditorInfo.IME_ACTION_GO 效果:
- actionSearch 搜索,对应常量EditorInfo.IME_ACTION_SEARCH 效果:
- actionSend 发送,对应常量EditorInfo.IME_ACTION_SEND 效果:
- actionNext 下一个,对应常量EditorInfo.IME_ACTION_NEXT 效果:
- actionDone 完成,对应常量EditorInfo.IME_ACTION_DONE 效果:
在代码中处理对应的action
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et_input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/hint"
android:inputType="text"
android:imeOptions="actionDone"/>
</RelativeLayout>
package com.example.imeoptions;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findView();
}
private void findView() {
EditText et_input = (EditText) findViewById(R.id.et_input);
et_input.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
switch (actionId) {
case EditorInfo.IME_ACTION_SEARCH:
Log.e(TAG, "ACTION_SEARCH");
break;
case EditorInfo.IME_ACTION_GO:
Log.e(TAG, "ACTION_GO");
break;
case EditorInfo.IME_ACTION_DONE:
Log.e(TAG, "ACTION_DONE");
break;
case EditorInfo.IME_ACTION_SEND:
Log.e(TAG, "ACTION_SEND");
break;
case EditorInfo.IME_ACTION_NEXT:
Log.e(TAG, "ACTION_NEXT");
case EditorInfo.IME_ACTION_NONE:
Log.e(TAG, "ACTION_NONE");
break;
default:
break;
}
return false;
}
});
}
}