Sagar Mehta
Sagar Mehta

Reputation: 455

Adding filter for Spinner and filter the data on spinner itself

I have a scenario where I want to filter the data when user types something. I am using Spinner currently, but what I want is user should be able to write data on spinner itself and data gets filtered at run time. I am not able to find anything similar to what I want.

Something similar to below image (It is an example of RadcomboBox used in ASP.net).

enter image description here

Upvotes: 1

Views: 11752

Answers (2)

Ganesh P
Ganesh P

Reputation: 196

You can achieve that using AutoCompleteTextView

 CustomAutoComplete autoComTextView = (CustomAutoComplete) view.findViewById(R.id.autoComTextView);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_dropdown_item_1line, myArray[1]);
        autoComTextView.setThreshold(1);
        autoComTextView.setAdapter(adapter);
        autoComTextView.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
                if (myArray[1].length > 0) {
                    if (!autoComTextView.getText().toString().equals(""))
                        adapter.getFilter().filter(null);
                    autoComTextView.showDropDown();
                }
                return false;
            }
        });
        autoComTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
                Toast.makeText(parent.getContext(),myArray[0][position],Toast.LENGTH_SHORT).show();

            }
        });

your view will be like this

            <com.package.name.CustomAutoComplete
                android:id="@+id/autoComTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="hint"
                android:imeOptions="actionSearch"
                android:inputType="textAutoComplete|textAutoCorrect"
                android:textColor="@color/BLACK"/>

CustomAutoComplete class should by like this

public class CustomAutoComplete extends android.support.v7.widget.AppCompatAutoCompleteTextView {

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

    public CustomAutoComplete(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
    }

    public CustomAutoComplete(Context arg0, AttributeSet arg1, int arg2) {
        super(arg0, arg1, arg2);
    }

    @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);
    }
    @Override
    public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom) {
        Drawable dropdownIcon = ContextCompat.getDrawable(getContext(), R.drawable.ic_arrow_drop_down_black_24dp);
        if (dropdownIcon != null) {
            right = dropdownIcon;
            right.mutate().setAlpha(150);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            super.setCompoundDrawablesRelativeWithIntrinsicBounds(left, top, right, bottom);
        } else {
            super.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
        }

    }

}

Upvotes: 0

sarika kate
sarika kate

Reputation: 479

You can achieve that using Edittext and Listview
when you type in EditText box as per that Listview will refesh the data. Consider initialty ArrayList<String> Citylist load in CityAdapter like below code.

CityAdapter adapter = new CityAdapter(getActivity(), R.layout.customlayout, Citylist );
listview.setAdapter(adapter);   

When you type in EditText Box listview will refresh data - use below code

     et_search.addTextChangedListener(new TextWatcher() {

                  public void afterTextChanged(Editable s) {
                  }

                  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                  }

                  public void onTextChanged(CharSequence s, int start, int before, int count) {

                      if(!s.toString().equals(""))
                      {
                          filterlist = new ArrayList<String>();

                          filterlist=  getFilter(s.toString());
                           CityAdapter adapter = new CityAdapter(getActivity(), R.layout.customlayout, filterlist);
                          listview.setAdapter(adapter); 


                          adapter.notifyDataSetChanged();
                      }
                      else
                      {
                           CityAdapter adapter = new CityAdapter(getActivity(), R.layout.customlayout, Citylist);
                          listview.setAdapter(adapter); 
                          adapter.notifyDataSetChanged();
                      }

                  }
                  });

Listview filter function is below -

 public  ArrayList<String> getFilter(CharSequence charSequence)
        {
         ArrayList<String> filterResultsData = new ArrayList<String>();;
                 if(charSequence == null || charSequence.length() == 0)
                    {
                        return null;
                    }
                    else
                    {


                        for(String data : Citylist)
                        {
                            //In this loop, you'll filter through originalData and compare each item to charSequence.
                            //If you find a match, add it to your new ArrayList
                            //I'm not sure how you're going to do comparison, so you'll need to fill out this conditional
                            if(data.toLowerCase().contains(charSequence))
                            {
                                filterResultsData.add(data);
                            }
                        }            

                    }

                    return filterResultsData;
                }

Upvotes: 6

Related Questions