Reputation: 123
I'm retrieving a list of custom objects from mobile service client hosted in Azure Cloud
, now I want to bind one of the property of this class to the Spinner
control in Android
client.
As my code below, I have a List<Departement>
coming from Azure mobile services, and I want to bind DepartmentName to this Spinner
in Android client.
public class Department
{
public int ID;
public String DepartmentName;
}
Any suggestion is highly appreciated
Upvotes: 2
Views: 3083
Reputation: 12347
You can either:
Override toString()
method in your custom object to return the good value based on your custom
property
public class Department
{
public int ID;
public String DepartmentName;
@Override
public String toString() {
return DepartmentName;
}
}
And then in your view
public void populateSpinner(Context context, List<Department> departments, Spinner spinner)
{
ArrayAdapter<Department> adapter = new ArrayAdapter<Department>(context, android.R.layout.simple_spinner_item, departments);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
Create a temporary List<String>
for your spinner adapter
public void populateSpinner(Context context, List<Department> departments, Spinner spinner)
{
List<String> list = new ArrayList<String>();
for(Department dep : departments) {
list.add(dep.DepartmentName);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
Last but not least, use your own adapter based on BaseAdapter
instead of using the generic ArrayAdapter
, that will own the list of custom objects and provide your spinner with the view.
Upvotes: 7