问题
I want to populate my Android spinner with data from a SQLite table. I already have the database controllers, and these are returning custom objects.
Now what I need to do is populate the spinner with this objects, in order to get not the string field, but the Id field. For example: My table Days, with fields Id and Day:
id - day 1 - Sunday
2 - Monday
3 - Tuesday...
And the Day object has two properties (id, and name)
I want the spinner to show "Monday", but internally, store the Id field '2' in an int variable, in order to query again the database with theese selected values.
I think I have to do it with an Adapter, but I don't know if I can do what I want with this controller.
I'd apreciate some order or advice to begin with.
Thanks
回答1:
You can use ArrayAdapter<T>
to populate your spinner via the method setAdapter
.
private List<MyData> data;
...
mySpinner.setAdapter<MyData>(new ArrayAdapter(getContext(), resId, data));
...
public class MyData {
private int _id;
public MyData(int id) {
this._id = id;
}
@Override
public String toString() {
switch (this._id) {
....
}
}
}
回答2:
You can do so with Custom Spinner. See this Design the spinner item separately in xml and use LayoutInflator.
回答3:
save: In the getView() of your Adapter use "setTag" method set the "Day object"
retrive:(onItemSelcted method of spinner) now by using getTag() method, get the "Day object" (Day object.getId() will return the int value)
回答4:
Finally I solved it following this tutorial.
http://adanware.blogspot.com.es/2012/03/android-using-spinner-with-custom.html
回答5:
in ArrayAdapter
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View v = super.getDropDownView(position, convertView, parent);
if (position > 0) {
((TextView) v.findViewById(android.R.id.text1)).setText(list.get(position - 1).getName());
}
return v;
}
来源:https://stackoverflow.com/questions/29077135/populate-spinner-with-custom-object