我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
一个简单的解决方法是只编辑Text.setEnabled(false);editText.setEnabled(true);在Button onClick()方法中。
其他回答
Meier的解决方案也适用于我。在我的例子中,我的应用程序的顶层是一个选项卡宿主,我想在切换选项卡时隐藏关键字-我从选项卡宿主视图获取窗口令牌。
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0);
}
}
下面的代码将帮助您创建可以从任何地方调用的通用函数。
import android.app.Activity
import android.content.Context
import android.support.design.widget.Snackbar
import android.view.View
import android.view.inputmethod.InputMethodManager
public class KeyboardHider {
companion object {
fun hideKeyboard(view: View, context: Context) {
val inputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
使用一行代码从任何地方调用Above方法。
CustomSnackbar.hideKeyboard(view, this@ActivityName)
视图可以是任何内容,例如活动的根布局。
只需在BaseActivity和BaseFragment中为整个应用程序创建通用方法
在onCreate()中初始化inputMethodManager
inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
使用此方法隐藏和显示键盘
public void hideKeyBoard(View view) {
if (view != null) {
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public void showKeyboard(View view, boolean isForceToShow) {
if (isForceToShow)
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
else if (view != null)
inputMethodManager.showSoftInput(view, 0);
}
以下是使用Kotlin隐藏软键盘的最简单方法:
//hides soft keyboard anything else is tapped( screen, menu bar, buttons, etc. )
override fun dispatchTouchEvent( ev: MotionEvent? ): Boolean {
if ( currentFocus != null ) {
val imm = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
imm.hideSoftInputFromWindow( currentFocus!!.windowToken, 0 )
}
return super.dispatchTouchEvent( ev )
}
您还可以研究在EditText上使用setImeOption。
我只是遇到了一个非常模拟的情况,我的布局包含一个EditText和一个搜索按钮。当我发现我可以在editText中将time选项设置为“actionSearch”时,我意识到我甚至不再需要搜索按钮。软键盘(在此模式下)有一个搜索图标,可用于启动搜索(键盘会自动关闭)。