以下代码片段只是隐藏键盘:
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
到该组件,一切都会就位。如果您想知道如何做到这一点,实际上非常简单。这就是你要做的,你编写一个如下所示的递归方法,事实上你可以用它来做任何事情,比如设置自定义字体等...这是方法
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>
并打电话setupUI(findViewById(R.id.parent))
, 就这些。
如果您想有效地使用它,您可以创建一个扩展Activity
并放入此方法,并使应用程序中的所有其他活动扩展此活动并调用其setupUI()
in the onCreate()
method.
如果您使用超过 1 个活动,请为父布局定义公共 id,例如<RelativeLayout android:id="@+id/main_parent"> ... </RelativeLayout>
然后扩展一个类Activity
并定义setupUI(findViewById(R.id.main_parent))
其内OnResume()
并扩展这个类而不是“Activity” 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)
}
}