我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
对于那些寻找喷气背包的人来说,写下答案。
val keyboardController = LocalSoftwareKeyboardController.current
//for showing the keyboard
keyboardController?.show()
//for hiding the keyboard
keyboardController?.hide()
其他回答
这种方法总是不惜任何代价。只要在你想隐藏键盘的地方使用它
public static void hideSoftKeyboard(Context mContext,EditText username){
if(((Activity) mContext).getCurrentFocus()!=null && ((Activity) mContext).getCurrentFocus() instanceof EditText){
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(username.getWindowToken(), 0);
}
}
这样使用:
无论Android版本是什么。这种方法肯定会奏效的
简单的方法是在EditText视图中设置以下属性。
android:imeOptions="actionDone"
用try-catch包围它,这样键盘就已经关闭,应用程序就不会崩溃:
try{
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
e.printStackTrace();
}
有很多答案,如果一切都不起作用,那么,这里有一个提示:),您可以制作EditText,
edittext.setAlpha(0f);
由于alpha方法,将看不到该编辑文本,现在使用上面的答案了解如何使用EditText显示/隐藏软键盘。
我的解决方案:
用活动构造它(视图是可选的),使用处理程序发布它(有一些延迟,例如100ms更好)。直接调用输入管理器有时不起作用。只有在工作时才能获得“活动”。我认为这很正常。
如果您可以在通话时获取根视图组或编辑视图,只需发送它即可获得更好的结果。
public class CloseSoftKeyboardRunnable implements Runnable
{
Activity activity;
View view; // for dialog will occur context getcurrentfocus == null. send a rootview to find currentfocus.
public CloseSoftKeyboardRunnable(Activity activity, View view)
{
this.activity = activity;
this.view = view;
}
public CloseSoftKeyboardRunnable(Activity activity)
{
this.activity = activity;
}
@Override
public void run() {
if (!activity.isFinishing())
{
InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (view == null) {
view = activity.getCurrentFocus();
}
else
{
try {
view = ((ViewGroup)view).getFocusedChild();
}
catch ( Exception e) {}
}
Window window = activity.getWindow();
if (window != null)
{
if (view == null) {
try {
view = window.getDecorView();
view = ((ViewGroup)view).getFocusedChild();
}
catch ( Exception e) {}
}
if (view == null) {
view = window.getDecorView();
}
if (view != null) {
if (view instanceof EditText)
{
EditText edittext = ((EditText) view);
edittext.setText(edittext.getText().toString()); // reset edit text bug on some keyboards bug
edittext.clearFocus();
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
}
}