以下代码段只是隐藏了键盘:
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
if(inputMethodManager.isAcceptingText()){
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(),
0
);
}
}
您可以将其放在实用程序类中,或者如果您在活动中定义它,请避免使用活动参数,或调用hideSoftKeyboard(this)
.
最棘手的部分是何时调用它。您可以编写一个遍历View
活动中的每个的方法,并检查它是否是一个,instanceof EditText
如果它没有setOnTouchListener
向该组件注册 a 并且一切都会到位。如果您想知道如何做到这一点,它实际上非常简单。这就是你要做的,你写一个像下面这样的递归方法,实际上你可以用它来做任何事情,比如设置自定义字体等......这是方法
public void setupUI(View view) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(MyActivity.this);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
就是这样,只需setContentView
在您的活动中调用此方法即可。如果您想知道要传递什么参数,它是id
父容器的参数。分配id
给您的父容器,例如
<RelativeLayoutPanel android:id="@+id/parent"> ... </RelativeLayout>
和 call setupUI(findViewById(R.id.parent))
,仅此而已。
如果您想有效地使用它,您可以创建一个扩展Activity
并将此方法放入,并让您的应用程序中的所有其他活动扩展此活动并setupUI()
在onCreate()
方法中调用它。
希望能帮助到你。
如果您使用超过 1 个活动,请为父布局定义公共 id,例如
<RelativeLayout android:id="@+id/main_parent"> ... </RelativeLayout>
然后扩展一个类并在其内Activity
定义并扩展这个类而不是``ActivitysetupUI(findViewById(R.id.main_parent))
OnResume()
in your program
这是上述函数的 Kotlin 版本:
@file:JvmName("KeyboardUtils")
fun Activity.hideSoftKeyboard() {
currentFocus?.let {
val inputMethodManager = ContextCompat.getSystemService(this, InputMethodManager::class.java)!!
inputMethodManager.hideSoftInputFromWindow(it.windowToken, 0)
}
}