您的位置:首页 > 其它

EditText设置IME动作问题

2016-06-08 22:03 295 查看
在Android Studio的Templates中的Login Activity中,看到了EditText中可以设置android:imeOptions、android:imeActionId以及android:imeActionLabel的属性来定义Enter键的内容

控件EditText设置如下

<pre name="code" class="html"><EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"/>

运行图如下所示,可以看到红色箭头所示的地方Enter键的内容是自定义的label值



监听函数如下所示

</pre><pre name="code" class="java"> mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});但是加了断点测试的时候,id的值总是是EditorInfo.IME_NULL的值,而不是EditText控件中定义的R.id.login的值,去掉android:imeOptions也依然只响应EditorInfo.IME_NULL的值
网上查了一些资料后发现,如果用android:imeOptions的默认属性,那么在onEditorAction的回调函数中得到的id值就只能是EditorInfo中已经定义好的那些值

如果要响应自定义的android:imeActionId的值,必须自己定义一个resources文件,如integers.xml,在里面定义id的值

<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="action_sign_in">100</integer>
</resources>
控件EditText设置如下

<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeActionId="@integer/action_sign_in"
android:imeActionLabel="@string/sign_in_short"
android:inputType="textPassword" />即可在onEditorAction的回调函数中响应自己定义的id的值
(即如果设置android:imeActionId="@+id/login",回调函数中的id值不会是R.id.login)

参考资料:https://plus.google.com/+CyrilMottier/posts/FBZrVnbUCXZ 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: