我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
碎片形式的科特林溶液:
fun hideSoftKeyboard() {
val view = activity?.currentFocus
view?.let { v ->
val imm =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager // or context
imm.hideSoftInputFromWindow(v.windowToken, 0)
}
}
检查您的清单是否没有与活动关联的此参数:
android:windowSoftInputMode="stateAlwaysHidden"
其他回答
一些科特林代码:
从“活动”中隐藏键盘:
(currentFocus ?: View(this))
.apply { (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(windowToken, 0) }
当您想手动隐藏键盘时,单击按钮:
/**
* Hides the already popped up keyboard from the screen.
*
*/
public void hideKeyboard() {
try {
// use application level context to avoid unnecessary leaks.
InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
assert inputManager != null;
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
e.printStackTrace();
}
}
当您想在屏幕上除编辑文本以外的任何地方隐藏键盘时在活动中重写此方法:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View view = getCurrentFocus();
if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
int scrcoords[] = new int[2];
view.getLocationOnScreen(scrcoords);
float x = ev.getRawX() + view.getLeft() - scrcoords[0];
float y = ev.getRawY() + view.getTop() - scrcoords[1];
if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
}
return super.dispatchTouchEvent(ev);
}
对于科特林爱好者。我创建了两个扩展函数。为了隐藏键盘的乐趣,您可以将edittext的实例作为视图传递。
fun Context.hideKeyboard(view: View) {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
hideSoftInputFromWindow(view.windowToken, 0)
}
}
fun Context.showKeyboard() {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
}
我的解决方案:
用活动构造它(视图是可选的),使用处理程序发布它(有一些延迟,例如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);
}
}
}
}
如果有人感兴趣的话,我已经为Kotlin写了一个小扩展,但没有太多测试:
fun Fragment.hideKeyboard(context: Context = App.instance) {
val windowToken = view?.rootView?.windowToken
windowToken?.let {
val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
}
App.instance是存储在Application中的静态“this”Application对象
更新:在某些情况下,windowToken为空。我增加了使用反射来检测键盘是否关闭的额外关闭方式
/**
* If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
*
* @param useReflection - whether to use reflection in case of no window token or not
*/
fun Fragment.hideKeyboard(context: Context = MainApp.instance, useReflection: Boolean = true) {
val windowToken = view?.rootView?.windowToken
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
windowToken?.let {
imm.hideSoftInputFromWindow(windowToken, 0)
} ?: run {
if (useReflection) {
try {
if (getKeyboardHeight(imm) > 0) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
}
} catch (exception: Exception) {
Timber.e(exception)
}
}
}
}
fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int