Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a custom object to a Spinner and showing a specific property

I have a spinner which I need to populate with String values, but also I need to conserve the id of that String.

I have this strucuture to show in the spinner

public class Item{

    private Integer id;

    private Double name;
}

I want to show the name in the spinner but when I select one item and press a button, i want to have the id of that name.

The String doesn't repite, so I can do a Map<Integer, String> to manange this, but I'm wondering if exists a better solution to this, like customing the adapter or the layout of the spinner or setting a sort of Data Source Object for the spinner and show a specific property of the object.

This is my spinner_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinnerTarget"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="12pt"
    android:gravity="center"/>
like image 312
LSikh Avatar asked Jan 02 '23 18:01

LSikh


1 Answers

Change your model class like this

public class Item{

private String id;
private String name;

 public String getId() {
    return id;
}

public String getName() {
    return name;
}

public String toString() {
return getName();
}

}

Set spinner adapter like this

ArrayAdapter<Item> adapter =
                        new ArrayAdapter<Item>(getActivity(), android.R.layout.simple_spinner_dropdown_item, dataNew);
spinner.setAdapter(adapter);

Now to get the selected item's id,

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
          //get id of the selected item using position 'i'
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
like image 60
Navneet Krishna Avatar answered Jan 05 '23 17:01

Navneet Krishna