AutoCompleteTextView:后退键上删除软键盘而不是建议

23

使用AutoCompleteTextView时,下拉建议列表与软键盘仍然可见。这很有意义,因为通常更有效率的方法是输入后续字符以缩小列表。

但是,如果用户想要浏览建议列表,当软键盘仍然存在时会变得非常繁琐(尤其是当设备处于横向方向时更为严重)。没有键盘占用屏幕空间时,浏览列表要容易得多。不幸的是,当您按下返回键时,默认行为首先移除列表(即使在返回键的软件版本中,它显示了说明“按下此键将隐藏键盘”的图像)。

以下是一个简单示例,演示了我所说的问题:

public class Main2 extends Activity {
    private static final String[] items = {
            "One",
            "Two",
            "Three",
            "Four",
            "Five"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AutoCompleteTextView actv = new AutoCompleteTextView(this);
        actv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        actv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
        actv.setThreshold(1);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.addView(actv);

        setContentView(ll);
    }
}

除了这种不直观的情况(后退键提示表明后退按键将发送到键盘),它还使得导航AutoCompleteTextView建议变得极其繁琐。

最不具侵入性的方法是什么(例如,在每个活动中捕获后退并相应地进行路由绝对不是理想的解决方案)以使第一次后退按键隐藏键盘,第二次后退按键则移除建议列表?


你找到解决方案了吗? - H.Fa8
2个回答

37

你可以通过覆盖自定义 AutoCompleteTextView 中的 onKeyPreIme 来实现。

public class CustomAutoCompleteTextView extends AutoCompleteTextView {

    public CustomAutoCompleteTextView(Context context) {
        super(context);
    }

    public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing()) {
            InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            
            if (inputManager.hideSoftInputFromWindow(findFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS)) {    
                return true;
            }
        }

        return super.onKeyPreIme(keyCode, event);
    }

}

1
刚在空白项目中尝试了一下,只使用了问题中的代码,它是可以正常工作的。在我更复杂的实例中可能有些冲突。尽管如此,感谢这个简单漂亮的解决方案! - btalb
这个方案不起作用,似乎从未调用过这个方法。 - user3402040
1
你让我的一天变得美好。非常感谢! - Kuls
1
太棒了!! - OhhhThatVarun
1
马沙阿拉赫,很棒,适用于Android 10的工作 - Noor Hossain
显示剩余9条评论

3

设置DismissClickListener的方法如下:

 autoCompleteTextView.setOnDismissListener(new AutoCompleteTextView.OnDismissListener() {
            @Override
            public void onDismiss() {
                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                in.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), 0);
            }
        });

1
这只适用于API17之后的版本。对于API < 17有什么解决方案吗?谢谢。 - Sachiin Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接