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"/>
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) {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With