第一步:布局文件
<EditText
android:id="@+id/et_drug_weight"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_weight="1"
android:gravity="center"
android:singleLine="true"
android:imeOptions="actionDone"
android:hint="0"
android:inputType="number"
android:maxLength="4"
android:textSize="14sp" />
imeOptions
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
但是,不同的输入法会用不同的方式实现以上行为,比如,有的actionSearch会是“搜索”文字,有的会是一个放大镜图标,有的actionDone会是“完成”文字,有的会是一个回车图标。
imeActionLabel
imeActionLabel不是用于自定义按钮文字的。
例如你设置android:imeActionLabel="添加",android:imeOptions="actionDone",则有些软键盘的Enter键会显示“添加”而不是“完成”或其它。
但是这种设置不是在所有手机上都有效果,一般手机自带的软键盘有效果的可能性很大,第三方软键盘有效果的可能性很小。
而且即使显示了“添加”也是有问题的。总之,不要试着用imeActionLabel自定义文字
如果你用了
android:imeOptions但是没有效果,则应该加上android:singleLine="true"。
当然,无论是imeOptions还是imeActionLabel等,都可以通过java代码实现,不一定要在布局文件中设置。
第二步:在代码中监听按键
以监听actionDone为例:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//TODO:你自己的业务逻辑
return true;
}
return false;
}
});