我有一个使用ViewPager的带有5个标签的应用。选项卡3具有一个EditText字段,因此用户可以使用软键盘输入文本。一旦失去EditText的焦点,我添加了一个setOnFocusChangeListener来隐藏键盘:
versesEdit.setOnFocusChangeListener((v, hasFocus) -> {
if(v.getId() == R.id.edittext_chew_verses && !hasFocus) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
});
当用户输入完文本并切换到另一个选项卡时,将调用监听器,并且键盘消失(到目前为止一切正常)。奇怪的是,一旦用户切换到左侧的选项卡,便不会调用监听器。一旦选择了选项卡1、4或5,就会按预期方式调用监听器,但是<选择选项卡2后,strong>未呼叫(请参阅所附屏幕截图)。这是我的EditText:
<EditText
android:id="@+id/edittext_chew_verses"
android:layout_width="match_parent"
android:layout_height="0dp"
android:singleLine="false"
android:layout_weight="1"
android:gravity="top"
android:hint="@string/chew_hint"
android:inputType="textMultiLine" />
有什么主意吗?谢谢] 1
答案 0 :(得分:1)
您可以使用ViewPager.onPageChangeListener:
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is page is not tab 3 and hide the soft keyboard
}
});
编辑1 :(第一条评论)
您可以使用此功能隐藏不带editText的软键盘:
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
view.clearFocus();
}