AutoCompleteTextView 强制显示所有项目

问题描述 投票:0回答:12

我的应用程序中有一个时刻,我需要强制显示建议列表中的所有项目,无论用户输入什么。我怎样才能做到这一点?

我尝试用过滤做一些事情,但对于我来说,作为初学者过滤太复杂了,我尝试搜索初学者教程进行过滤,但没有任何运气。也许,有一种更简单的方法来强制显示所有建议项?

编辑: 基本上我的想法是,当用户输入列表中没有的内容时,它会显示他可以拥有的所有可用选项。

我找到了检查 ACTV 是否显示的最佳方法,但在 TextChangeEvent 上,我将用户输入的文本与我的列表进行比较,然后如果没有找到元素,则显示完整列表。

public void onTextChanged(CharSequence s, int start, int before, int count)
         {                
           final EditText editText = (EditText) findViewById(R.id.vardsUserInput);
            String strValue = editText.getText().toString().toUpperCase();
            String temp;
            int Cc=0; //my count variable
            for(int i=0; i<vardi.length; i++)
            {
                temp = vardi[i].toUpperCase();
                if(temp.startsWith(strValue.toUpperCase()))
                {
                    Log.d("testing",vardi[i]);
                    Cc++;                                                   
                }
            }               
        if(Cc == 0)
        {
        //Show all the available options
    textView.showDropDown();                    
         }                  
}
java android autocompletetextview
12个回答
15
投票

您没有定义要显示所有结果的“时刻”,所以我希望这适合。但尝试这样的事情:

AutoCompleteTextView autoComplete;
String savedText;

public void showAll() {
    savedText = autoComplete.getText().toString();
    autoComplete.setText("");
    autoComplete.showDropDown();
}

public void restore() {
    autoComplete.setText(savedText);
}

15
投票

这对我来说非常有效,这是解决问题的简单方法:

final ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, usernameLists);
    etUsername.setThreshold(1);
    etUsername.setAdapter(adapter);
    etUsername.setOnTouchListener(new View.OnTouchListener() {

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
            if (usernameLists.size() > 0) {
                // show all suggestions
                if (!etUsername.getText().toString().equals(""))
                    adapter.getFilter().filter(null);
                etUsername.showDropDown();
            }
            return false;
        }
    });

14
投票

要阻止适配器过滤,您可以在文本视图上设置足够高的阈值:

autoCompleteTextView.setThreshold(100);

希望有帮助。


9
投票

基本上,经过 5-6 小时的实验来了解该死的过滤器是如何工作的,我编写了自己的适配器,它正是我想要的:

    import android.content.Context;
    import android.widget.ArrayAdapter;
    import android.widget.Filter;
    import android.widget.Filterable;
    
    import java.util.ArrayList;
    
    public class BurtuAdapteris extends ArrayAdapter<String> implements Filterable {
        ArrayList<String> _items = new ArrayList<>();
        ArrayList<String> orig = new ArrayList<>();
    
        public BurtuAdapteris(Context context, int resource, ArrayList<String> items) {
            super(context, resource, items);
    
            for (int i = 0; i < items.size(); i++) {
                orig.add(items.get(i));
            }
        }
    
        @Override
        public int getCount() {
            if (_items != null)
                return _items.size();
            else
                return 0;
        }
    
        @Override
        public String getItem(int arg0) {
            return _items.get(arg0);
        }
    
        @Override
        public Filter getFilter() {
            Filter filter = new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
    
                    FilterResults oReturn = new FilterResults();
                    String temp;
                    int counters = 0;
                    if (constraint != null) {
    
                        _items.clear();
                        if (orig != null && orig.size() > 0) {
                            for (int i = 0; i < orig.size(); i++) {
                                temp = orig.get(i).toUpperCase();
    
                                if (temp.startsWith(constraint.toString().toUpperCase())) {
    
                                    _items.add(orig.get(i));
                                    counters++;
    
                                }
                            }
                        }
                        if (counters == 0) {
                            _items.clear();
                            _items = orig;
                        }
                        oReturn.values = _items;
                        oReturn.count = _items.size();
                    }
                    return oReturn;
                }
    
                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    if (results != null && results.count > 0) {
                        notifyDataSetChanged();
                    } else {
                        notifyDataSetInvalidated();
                    }
    
                }
    
            };
    
            return filter;
        }
    
    }

而且使用简单,只需用这个替换原来的适配器即可:

    final BurtuAdapteris fAdapter = new burtuAdapteris(this, android.R.layout.simple_dropdown_item_1line, liste);

就我而言,

liste
是:
ArrayList<String> liste = new ArrayList<String>();


3
投票

方法强制显示下拉列表。

你需要调用 requestFocus();显示键盘,否则键盘不会弹出。

autocomptv.setOnTouchListener(new OnTouchListener() {

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
            // TODO Auto-generated method stub
            autocomptv.showDropDown();
            autocomptv.requestFocus();
            return false;
        }
    });

3
投票

正如“ArtOfWarfare”所建议的,您可以直接子类化并重写performFiltering():

public class My_AutoCompleteTextView extends AutoCompleteTextView {
    public My_AutoCompleteTextView(Context context) {
        super(context);
    }
    public My_AutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public My_AutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void performFiltering(CharSequence text, int keyCode) {
        super.performFiltering("", 0);
    }
}

我正在成功使用它。


2
投票

如果你想立即显示建议,那么你必须重写

enoughToFilter()
以使其始终返回true。要忽略作为文本输入给出的内容,您必须使用
performFiltering("", 0)
和空过滤模式。然后 AutoCompleteTextView 显示所有建议。

这是我从其他 StackOverflow 帖子中组合而成的解决方案:

public class InstantAutoComplete extends android.support.v7.widget.AppCompatAutoCompleteTextView {
    public InstantAutoComplete(Context context) {
        super(context);
    }

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

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

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);

        if (focused && getAdapter() != null) {
            performFiltering("", 0);
        }
    }
}

2
投票

这对我有用:

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

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused) {
            performFiltering(getText(), 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.showDropDown();
        return super.onTouchEvent(event);
    }
}

2
投票

简单易行的答案是:

之后

autoCompleteTextView.setText("")
只需从适配器上取下过滤器,如下所示:

autoCompleteTextView.adapter.filter.filter(null)

就是这样,过滤消失并显示整个下拉列表。


0
投票
class InstantAutoComplete(context: Context?, attrs: AttributeSet?) : AutoCompleteTextView(context, attrs) {

override fun enoughToFilter(): Boolean {
    return true
}

override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect)
    if (focused && filters != null) {
        performFiltering(text, 0)
    }
}

fun performFilter() {
    performFiltering(text, 0)
    showDropDown()
}

}

单击按钮下拉菜单(图像视图)后,我需要显示自动完成文本视图中的所有数据。使用类扩展 AutoCompleteTextView 并添加此功能,它就像魔术一样。


0
投票
  1. autoComplete.setText(" ")
  2. 过滤器 { it.contains(constraint.trim(), true) } }

注意:您必须使用空格文本设置自动完成文本,并且在过滤器中,您应该修剪约束文本输入,它将显示所有下拉列表。


0
投票

参考上面的答案:https://stackoverflow.com/a/60223651/9166855 通过一些额外的更改,我能够获得完美的可行解决方案:

  1. XML:在 AutoCompleteTextView 中添加以下代码。这可以避免用户手动输入任何内容并仅选择建议。

    android:inputType="none"
    android:focusableInTouchMode="false"
    android:cursorVisible="false"
    
  2. 代码:设置高阈值有助于始终显示所有建议。

    autotvLocations.setThreshold(100);  // Setting high threshold so that everytime all suggestions are shown.
    
© www.soinside.com 2019 - 2024. All rights reserved.