jaredrummler / MaterialSpinner

A spinner view for Android
Apache License 2.0
1.33k stars 217 forks source link

How to set items from custom ArrayList #109

Open bviral opened 5 years ago

bviral commented 5 years ago

Hello Sir,

I am getting data directly from db so I am having that data in custom ArrayList not in string type ArrayList. I don't want to convert it in single column List so please tell me how to set items by specifying custom type arraylist column.

ovicko commented 5 years ago

You need to create an Adapter of MaterialSpinnerAdapter Example you have:

 ArrayList<Country> countryArrayList = new ArrayList<>();
        Country country = new Country("Kenya",254);
        countryArrayList.add(country);
        Country country1 = new Country("Nigeria",244);
        countryArrayList.add(country1);
       MaterialSpinnerAdapter<County> countyMaterialSpinnerAdapter;
        countyMaterialSpinnerAdapter = new MaterialSpinnerAdapter<County> 
       (getContext(),countyArrayList);
        MaterialSpinner countrySpinner = view.findViewById(R.id.countrySpinner);
        countrySpinner.setAdapter(countryMaterialSpinnerAdapter);

        countrySpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<Country>() {

            @Override public void onItemSelected(MaterialSpinner view, int position, long id, Country country) {
                Snackbar.make(view, "Clicked " + country.getName() + " code = "+country.getCode(), Snackbar.LENGTH_LONG).show();
            }
        });
ovicko commented 5 years ago

Remember the Country model class has this method

//to display object as a string in spinner
    @Override
    public String toString() {
        return name;
    }
ovicko commented 5 years ago

More reference StackOverflow