ListPopupWindow关闭软键盘

时间:2018-07-07 10:40:10

标签: android lockscreen android-popupwindow

使用锁屏应用程序时,我看到一个非常奇怪的行为:显示ListPopupWindow会强制关闭软键盘。这仅在“锁屏”活动(活动窗口标志设置为FLAG_SHOW_WHEN_LOCKED | FLAG_DISMISS_KEYGUARD)上发生,并且仅在设置了键盘锁PIN /密码的情况下才会发生。

这是一个代码示例:

editText.setOnFocusChangeListener((v, hasFocus) -> {
        ListPopupWindow popupWindow = new ListPopupWindow(getContext());
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        popupWindow.setAdapter(new ArrayAdapter(
            getContext(), android.R.layout.simple_dropdown_item_1line, Arrays.asList("aaa", "bbb", "ccc")));
        popupWindow.setAnchorView(editText);
        popupWindow.show();
});

出现弹出列表时,键盘立即消失。

请注意,同时PopupWindow可以正常工作:

editText.setOnFocusChangeListener((v, hasFocus) ->  {
        PopupWindow popupWindow = new PopupWindow(getContext());
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        popupWindow.setContentView(new TextClock(getContext()));
        popupWindow.showAsDropDown(editText);
});

弹出窗口和键盘都可见。

关于如何避免此键盘消失的任何想法?最后,我需要一个SearchView(它在ListPopupWindow中显示建议)才能在锁定屏幕上正常工作。

1 个答案:

答案 0 :(得分:0)

我发现如果弹出窗口输入法模式为,键盘没有关闭 INPUT_METHOD_FROM_FOCUSABLE。

SearchView包含AutoCompleteTextView,可将其建议弹出窗口输入法模式更改为INPUT_METHOD_NEEDED或INPUT_METHOD_NOT_NEEDED。因此,解决方法是保留PopupWindow.mInputMethodMode = INPUT_METHOD_FROM_FOCUSABLE。

我通过创建一个具有setInputMethodMode()的自定义PopupWindow来解决了这一问题:

public class SearchSuggestionPopupWindow extends PopupWindow {

    SearchSuggestionPopupWindow(final Context context, final PopupWindow original) {
        super(context);

        setElevation(original.getElevation());

        setAnimationStyle(original.getAnimationStyle());

        setBackgroundDrawable(original.getBackground());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setOverlapAnchor(original.getOverlapAnchor());
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            setEnterTransition(original.getEnterTransition());
            setExitTransition(original.getExitTransition());
        }
    }

    @Override
    public void setInputMethodMode(final int mode) {
        super.setInputMethodMode(PopupWindow.INPUT_METHOD_FROM_FOCUSABLE);
    }
}

然后有必要从SearchView中获取AutoCompleteTextView:

final AutoCompleteTextView textView = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);

并替换自定义弹出窗口:

final Field listPopupField = AutoCompleteTextView.class.getDeclaredField("mPopup");
listPopupField.setAccessible(true);
final ListPopupWindow listPopup = (ListPopupWindow) listPopupField.get(textView);

final Field popupField = ListPopupWindow.class.getDeclaredField("mPopup");
popupField.setAccessible(true);
final PopupWindow popup = (PopupWindow) popupField.get(listPopup);
final PopupWindow customPopup = new SearchSuggestionPopupWindow(textView.getContext(), popup);
popupField.set(listPopup, customPopup);