AutoCompleteTextView force to show all items

我怕爱的太早我们不能终老 提交于 2019-12-03 06:15:25

问题


There is a moment in my app, that I need to force to show all items in the suggestion list, no matter what the user has typed. How can I do that?

I tried to do something with filtering, but for me as a beginner filtering is just way too complicated, I tried searching beginners tutorial for filtering without any luck. Maybe, there is a simpler way to force to show all the suggestion items?

EDIT: Basically what was my idea, is that, when user types something whats not in the list, it shows all the available options he can have.

I've found the best way of checking weather the ACTV is beign shown or not, but onTextChangeEvent I compare the user typed text with my list, and then if no elements have been found show full list.

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();                    
         }                  
}

回答1:


You don't define the "moment" when you want to display all the results, so I hope this fits. But try something like this:

AutoCompleteTextView autoComplete;
String savedText;

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

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



回答2:


Basically, after 5-6 hours of experimentation to understand how the damn filter works, I wrote my own adapter which does exactly what I want:

    public class burtuAdapteris extends ArrayAdapter<String> implements Filterable {

       ArrayList<String> _items = new ArrayList<String>();
       ArrayList<String> orig = new ArrayList<String>();

       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) {

                  if(constraint != null)
                      Log.d("Constraints", constraint.toString());
                  FilterResults oReturn = new FilterResults();

                /*  if (orig == null){
                    for (int i = 0; i < items.size(); i++) {
                        orig.add(items.get(i));
                    }
                  }*/
                  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++;

                                }
                            }
                      }
                      Log.d("REsult size:" , String.valueOf(_items.size()));
                          if(!counters)
                          {
                             _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;

      }


 }

And it's simple to use, just replace original adapter with this:

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

In my case liste is: ArrayList<String> liste = new ArrayList<String>();




回答3:


This works for me perfectly, this is an easy way to resolve the problem:

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;
        }
    });



回答4:


method forcefully show drop down list.

you need to call requestFocus(); to show keyboard otherwise keyboard does not pop up.

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;
        }
    });



回答5:


As "ArtOfWarfare" suggested, you can just sub-class and override 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);
    }
}



回答6:


If you want to show the suggestions instantly, then you have to override enoughToFilter() to make it always return true. To ignore what is given as text input, you have to use performFiltering("", 0) with an empty filtering pattern. The AutoCompleteTextView then shows all suggestions.

This is solution I've combined from other StackOverflow posts:

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);
        }
    }
}



回答7:


This is what worked for me:

    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);
    }
}



回答8:


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()
}

}

I need to show all data from autocompletetextview after click button dropdown(imageview). Using class extends AutoCompleteTextView and add this function, it works like magic.




回答9:


It's actually even easier than Sam listed. Whenever you want to show all, just do:

performFiltering("", 0);

When the filtering finishes it'll automatically display the drop down with all of the items visible.



来源:https://stackoverflow.com/questions/11284368/autocompletetextview-force-to-show-all-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!