AutoCompleteTextView:删除背面的软键盘而不是建议

时间:2014-11-23 07:16:47

标签: android keyboard android-softkeyboard autocompletetextview onbackpressed

使用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建议非常无聊。

什么是最少侵入性方式(例如,在每个活动中追上onBackPressed()并相应地路由它绝对不是理想的选择)让第一次按下隐藏键盘,第二个删除建议清单?

2 个答案:

答案 0 :(得分:30)

您可以通过在自定义onKeyPreIme中覆盖AutoCompleteTextView来实现这一目标。

    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 :(得分:3)

像这样设置DismissClickListener

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