Chivorns / SmartMaterialSpinner

The powerful android spinner library for your application
https://github.com/Chivorns/SmartMaterialSpinner
Other
333 stars 56 forks source link

How to populate a mutable list of objects #8

Closed PranavMalayil closed 3 years ago

PranavMalayil commented 4 years ago

How can i use a array list of objects to bind with this library

Chivorns commented 4 years ago

Hi @PranavMalayil currently it not support for array list of object to display with specific field. I am planing to have this feature support in the next release. If you set item as array list of object in this release, it will display all object fields in the dropdown list.

Chivorns commented 3 years ago

Hi @PranavMalayil , please find my sample bellow:

1. Create model for spinner item with any field you need and override toString() method to return default value to display on spinner.

My sample bellow, I display label base on my app language. If you prefer to to have base label instead, you can just return with labelEninstead.

public class SpinnerItem {
    private String labelEn;
    private String labelKh;
    private String labelCh;

    public SpinnerItem(String labelEn, String labelKh, String labelCh) {
        this.labelEn = labelEn;
        this.labelKh = labelKh;
        this.labelCh = labelCh;
    }

    public String getLabelEn() {
        return labelEn;
    }

    public void setLabelEn(String labelEn) {
        this.labelEn = labelEn;
    }

    public String getLabelKh() {
        return labelKh;
    }

    public void setLabelKh(String labelKh) {
        this.labelKh = labelKh;
    }

    public String getLabelCh() {
        return labelCh;
    }

    public void setLabelCh(String labelCh) {
        this.labelCh = labelCh;
    }

    @Override
    public String toString() {
        String label;
        if (App.getLanguage().equals(PreferenceManager.KHMER_LOCALE)) {
            label = labelKh;
        } else if (App.getLanguage().equals(PreferenceManager.CHINESE_LOCALE)) {
            label = labelCh;
        } else {
            label = labelEn;
        }

        if (StringsUtil.isBlank(label)) {
            label = labelEn;
        }
        return label;
    }

    /*@Override
    public String toString() {
        return labelEn;
    }*/
}

2. Your activity or fragment

SmartMaterialSpinner<SpinnerItem> spTitle;
private void initTitleSpinner() {
    // bind spinner with view or create new object

    List<SpinnerItem> titleItem = new ArrayList<>();
    titleItem.add(new SpinnerItem("Mr", "លោក", null));
    titleItem.add(new SpinnerItem("Mrs", "លោកស្រី", null));
    titleItem.add(new SpinnerItem("Miss", "កញ្ញា", null));
    spTitle.setItem(titleItem);
}