KMI
KMI

Reputation: 506

Sorting ListBiew by Spinner in android?

I have one ListView and one Spinner. The Spinner is situated at the right top of the layout. My ListView contains some names (eg. country names) and the spinner has some alphabets (a-z). Suppose if I choose the letter "f" from the Spinner, my ListView must show the country names that starts only with the letter "f" . I want to sort my ListView by values from the Spinner?

Upvotes: 0

Views: 2099

Answers (2)

user
user

Reputation: 87064

Try to use the getFilter() method of the ListView adapter:

        String[] filterL = { "a", "b", "c" }; //etc
        //...

        Spinner spin = (Spinner) findViewById(R.id.spinner1);
        final ArrayAdapter<String> aspin = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filterL); //the adapter for the Spinner
        aspin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(aspin);
        final ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, countries); //the adapter for the list
        setListAdapter(aa); //set the adapter for the list(if you extend LisActivity) or call setAdapter on the ListView element
        //add the listener:
        spin.setOnItemSelectedListener(new OnItemSelectedListener() {
            boolean status = false;

            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long arg3) {
                if (!status) {
                    status = true;
                    return;
                }

                aa.getFilter().filter(filterL[position]);
            }

            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });

Upvotes: 1

Tim
Tim

Reputation: 6712

You need to implement a Filter for your ListView. Everytime the OnItemSelectedListener of your Spinner gets called you need to filter the items. If you're not sure how to implement a filter in your ListView's adapter have a look at this: Filtering ListView with custom (object) adapter

I guess there won't be any way around implementing an own ListAdapter (it's easy).

Upvotes: 1

Related Questions