首页 > 解决方案 > Why does text keyboard show on Android's TimePicker's onScroll?

问题描述

When using a TimePicker set to spinner mode, if I click on a number (minutes or hours), the number keyboard shows up.

But whenever I scroll any of the spinners, the keyboard changes to the text inputType.

How can I avoid this?

I've tried calling timePicker.setAddStatesFromChildren(true) and setting an OnTimeChangedListener, but that won't work, for if I scroll just enough for the spinner to move but not for the time to change, the listener is not triggered but the keyboard changes to text inputType anyway.

Also, timePicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS) is not what I'm looking for, for I still want the keyboard to show up, but only that it won't change its inputType to text.

标签: androidandroid-softkeyboardtimepicker

解决方案


最后,我找不到使键盘出现的视图。我尝试从 TimePicker 内的每个视图中删除下一个焦点,但没有。CustomTextView然后,我认为问题在于,由于我使用的是 24 小时格式微调器,因此应归咎于TimePicker. 我使它无法聚焦,但仍然是同样的问题。所以我得出结论,问题出在 TimePicker 本身的实现中,它管理一些事件并显示键盘。

所以我决定迭代NumberPicker里面的 s TimePicker——它们是三个——并OnScrollListener在它们上设置一个隐藏键盘的值。但是,我仍然可以看到文本键盘在被解雇之前出现。但这是我能做到的最好的。

public static <T extends View> List<T> getViewsByClassNameFromView(ViewGroup viewGroup, Class<T> clazz) {

    final List<T> matches = new LinkedList<>();

    final int childCount = viewGroup.getChildCount();

    for (int i = 0; i < childCount; i++) {
        final View child = viewGroup.getChildAt(i);
        if (clazz.isInstance(child)) {
            matches.add((T) child);
        } else if (child instanceof ViewGroup) {
            matches.addAll(getViewsByClassNameFromView((ViewGroup) child, clazz));
        }
    }

    return matches;
}

public void hideSoftKeyboard(View view) {
    InputMethodManager imm =
            (InputMethodManager) view.getContext().getApplicationContext()
                    .getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    view.clearFocus();
}

private void fixTimePicker() {
    final List<NumberPicker> numberPickers = ViewUtil.getViewsByClassNameFromView(timePicker, NumberPicker.class);
    for (final NumberPicker numberPicker: numberPickers) {
        numberPicker.setOnScrollListener(new NumberPicker.OnScrollListener() {
            @Override
            public void onScrollStateChange(NumberPicker view, int scrollState) {
                hideSoftKeyboard(view);
            }
        });
    }
}

推荐阅读