How do I make an Android EditView 'Done' button and hide the keyboard when clicked?
当用户单击
问题是,当用户完成书写后,无法隐藏键盘。 用户必须按下"后退"按钮才能隐藏键盘。
有没有一种方法可以在键盘上显示
首先,您需要为目标EditText设置
1 2 3 4 5 6 7 | <EditText android:id="@+id/edittext_done" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Enter some text" android:imeOptions="actionDone" /> |
使用TextView.setImeOptions并将其传递给actionDone。
像
同时包含
1 2 3 4 5 6 7 | <EditText android:id="@+id/edittext_done" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionDone" android:singleLine="true" /> |
1 2 | android:imeActionLabel="Done" android:singleLine="true" |
在XML文件中工作正常。但这也会导致
1 2 | mainText.setHorizontallyScrolling(false); mainText.setMaxLines("Maximum integer value that you want to provide"); |
用这个:
1 | android:singleLine="true" |
为了完成按钮
和
xml中的
用于处理键盘点击完成
1 2 3 4 5 6 7 8 9 10 | editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event){ if(actionId == EditorInfo.IME_ACTION_DONE){ // Your action on done return true; } return false; } }); |
`
在您的
1 2 | android:imeActionLabel="Done" android:singleLine="true" |
或者您可以通过此行以编程方式实现它。
1 | editText.setImeOptions(EditorInfo.IME_ACTION_DONE); |
如果小部件的属性未更改,则最好使用
布局
采用:
1 2 | android:imeActionLabel="Done" android:singleLine="true" |
我必须指出,许多人在不知不觉中就可以为此奋斗。
如果您希望在单击
因此,仅设置
当时单击键盘上的下一个按钮时将使用ActionDone
键盘处于隐藏状态。在"编辑文本"或AppcompatEdit中使用
XML
1.1如果您使用AppCompatEdittext
1 2 3 4 5 | <android.support.v7.widget.AppCompatEditText android:id="@+id/edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:imeOptions="actionDone"/> |
1.2如果您使用Edittext
1 2 3 4 5 | <EditText android:id="@+id/edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:imeOptions="actionDone"/> |
JAVA
1 2 | EditText edittext= (EditText) findViewById(R.id.edittext); edittext.setImeOptions(EditorInfo.IME_ACTION_DONE); |
对于代码:
1 | editText.setImeOptions(EditorInfo.IME_ACTION_DONE); |
实际上,您可以将自定义文本设置为该蓝色小按钮。在xml文件中,只需使用
1 | android:imeActionLabel="whatever" |
在您的EditText上。
还是在java文件中使用
1 | etEditText.setImeActionLabel("whatever", EditorInfo.IME_ACTION_DONE); |
我随意选择IME_ACTION_DONE作为该函数的第二个参数应包含的示例。这些操作的完整列表可以在此处找到。
应当注意,这不会导致文本出现在所有设备上的所有键盘上。某些键盘不支持该按钮上的文本(例如swiftkey)。而且某些设备也不支持。一个好的规则是,如果您已经在按钮上看到了文本,这会将其更改为您想要的任何内容。