从“AutoCompleteTextView"获取当前建议 [英] Getting current suggestion from `AutoCompleteTextView`

查看:23
本文介绍了从“AutoCompleteTextView"获取当前建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 AutoCompleteTextView 中获得当前最热门的建议?我有它建议项目,并且我注册了一个文本更改侦听器.我在同一屏幕上也有一个列表.当他们输入时,我想将列表滚动到当前的最佳"建议.但我无法弄清楚如何访问当前的建议,或者至少是最重要的建议.我想我正在寻找类似 AutoCompleteTextView.getCurrentSuggestions() 的东西:

How do you get the current top suggestion in an AutoCompleteTextView? I have it suggesting items, and I have a text change listener registered. I also have a list on the same screen. As they type, I want to scroll the list to the current "best" suggestion. But I can't figure out how to access the current suggestions, or at least the top suggestion. I guess I'm looking for something like AutoCompleteTextView.getCurrentSuggestions():

autoCompleteTextView.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) {
            String currentText = autoCompleteTextView.getText();
            String bestGuess = autoCompleteTextView.getCurrentSuggestions()[0];
            //                                      ^^^ mewthod doesn't exist
            doSomethingWithGuess(bestGuess);
        }
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // do nothing
        }
        public void afterTextChanged(Editable s) {
            // do nothing
        }
    });

推荐答案

我已经用下面的代码完成了你想做的事情:

I've done what you want to do with the following code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.autocomplete_1);

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_dropdown_item_1line, COUNTRIES);
    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
    textView.setAdapter(adapter);

    adapter.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            Log.d(TAG, "dataset changed");
            Object item = adapter.getItem(0);

            Log.d(TAG, "item.toString "+ item.toString());
        }
    });
}

item.toString 将打印显示在第一项上的文本.

item.toString will print the text that is displayed on the first item.

请注意,即使您尚未显示弹出窗口(建议),也会发生这种情况.此外,您应该检查是否有任何项目通过了过滤条件(也就是用户的输入).

Note that this will happen even if you aren't showing the pop-up (suggestions) yet. Also, you should check if there are any items that passed the filter criteria (aka the user's input).

解决第一个问题:

    int dropDownAnchor = textView.getDropDownAnchor();
    if(dropDownAnchor==0) {
        Log.d(TAG, "drop down id = 0"); // popup is not displayed
        return;
    }
    //do stuff

解决第二个问题,使用 getCount > 0

To solve the second problem, use getCount > 0

这篇关于从“AutoCompleteTextView"获取当前建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆