问题描述
我在Activity
中有一个EditText
,我希望它可以处于活动状态,并且在打开Activity
时可以打开软键盘.这是我的xml
for EditText
:
I have an EditText
in an Activity
and I want it to be active and soft-keyboard be open when I open that Activity
. Here is my xml
for EditText
:
<EditText
android:background="@null"
android:cursorVisible="true"
android:elegantTextHeight="true"
android:enabled="true"
android:focusable="true"
android:hint="Search"
android:id="@+id/editText11"
android:inputType="textNoSuggestions|textCapSentences"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:singleLine="true"
android:textColor="#000000"
android:textCursorDrawable="@null" />
,并且我已将android:windowSoftInputMode="stateVisible"
用于具有此EditText
的活动.
and I have used android:windowSoftInputMode="stateVisible"
for the activity in which I have this EditText
.
问题是,当我按下back
一次时,键盘没有隐藏(理想情况下在所有其他EditText
中都隐藏了),而当我再次按下back
时,它关闭了Activity
.第一次按back
时,我不接到onBackPressed()
的电话,而第二次按back
时,我这样做.为什么会发生这种行为以及如何解决?
The problem is, when I press back
once, the keyboard does not hide(ideally it does in all other EditText
s) and when I press back
again, it closes the Activity
. On the first back
press, I am not getting a call to onBackPressed()
while on the second back
press, I do. Why is this kind of behaviour is happening and how to resolve it?
编辑,我想要的是,如果键盘是打开的,请按回去以关闭键盘,如果键盘没有打开,请关闭活动.
Edit What I want is, if keyboard is open, pressing back should close the keyboard and if the keyboard is not open, then close the activity.
推荐答案
尝试一下...
创建一个名为Util的类,并放置以下代码
public static void hideSoftKeyboard(Activity activity) {
final InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (inputMethodManager.isActive()) {
if (activity.getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
}
,然后调用Activity的onBackPressed()
这篇关于按下时隐藏软键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!