以下代码片段只是隐藏了键盘:
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
并将此方法放入,并使应用程序中的所有其他活动扩展此活动并在onCreate()
方法中调用它的setupUI()
.
希望能有所帮助.
如果使用多个活动,请定义父布局的公共id,如
然后从Activity
扩展一个类,在其OnResume()
中定义setupUI(findViewById(R.id.main_parent))
,并扩展这个类,而不是``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)
}
}