Android: How to Bind Spinner to Custom Object List

Android: How to bind spinner to custom object list?

You can look at this answer. You can also go with a custom adapter, but the solution below is fine for simple cases.

Here's a re-post:

So if you came here because you want to have both labels and values in the Spinner - here's how I did it:

  1. Just create your Spinner the usual way
  2. Define 2 equal size arrays in your array.xml file -- one array for labels, one array for values
  3. Set your Spinner with android:entries="@array/labels"
  4. When you need a value, do something like this (no, you don't have to chain it):

      String selectedVal = getResources().getStringArray(R.array.values)[spinner.getSelectedItemPosition()];

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

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) {

}
});

How to bind custom object to spinner layout using databinding library?

You have to wrap your entire layout in layout tag to use Data Binding.This way you can assign the Model to your View So this should be your layout.

<layout>
<data>
<variable name="data" type="your.packagename.Data">
</variable>
</data>
<!-- horisontal orientation -->
<LinearLayout>
<!-- Icon -->
<ImageView
android:src="@{data.imageUri}"/>

<!-- Title -->
<TextView
android:text="@{data.title}"/>

<!-- TotalCount -->
<TextView
android:text="@{data.totalCount}"/>

</LinearLayout>
</layout>

Lets assume your are using Activity to show the Spinner & your layout name is custom_spinner.xml . Then here is how you set the data to layout. After setting the Spinner Adapter, here is what you need to do

Data data; // Data object
CustomSpinnerBinding binding = DataBindingUtil.inflate(R.layout.custom_spinner);
binding.setData(data);

This should be your custom Adapter

@Override
public View getView(int position, View convertView, ViewGroup parent) {
CustomSpinnerBinding binding = DataBindingUtil.inflate(R.layout.custom_spinner);
binding.setData(dataList.get(position)); // you should pass dataList as an argument in Custom Adapter constructor
}

How do I bind a property of custom class List to Spinner in Android?

You can either:

  1. 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);
    }
  2. 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);
    }
  3. 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.

Use object array list as spinner adapter

Hi what you need to do is pretty easy, to your class Contact, override the toString() method in it and return the name of the contact.

look at the example. it is also available in github

public class SpinnerTestOneActivity extends AppCompatActivity {

private Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test_one);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_custom_toolbar);
setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

initializeUI();
}

private void initializeUI() {

spinner = (Spinner) findViewById(R.id.SpinnerTestOneActivity_spinner);

ArrayList<Contact> contacts = new ArrayList<>();

for (int i = 0; i < 10; i++) {
contacts.add(new Contact("Name_" + i, "Id_" + i));
}

ArrayAdapter<Contact> adapter =
new ArrayAdapter<Contact>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, contacts);
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(adapter);

}

private class Contact {
private String contact_name;
private String contact_id;

public Contact() {
}

public Contact(String contact_name, String contact_id) {
this.contact_name = contact_name;
this.contact_id = contact_id;
}

public String getContact_name() {
return contact_name;
}

public void setContact_name(String contact_name) {
this.contact_name = contact_name;
}

public String getContact_id() {
return contact_id;
}

public void setContact_id(String contact_id) {
this.contact_id = contact_id;
}

/**
* Pay attention here, you have to override the toString method as the
* ArrayAdapter will reads the toString of the given object for the name
*
* @return contact_name
*/
@Override
public String toString() {
return contact_name;
}
}

}

output

contact_image

Spinner with custom objects list inside custom Dialog Fragment not working

Thanks to a good night's sleep, some clearer headed thinking, and @Sam's answer (https://stackoverflow.com/a/14676975/3438497) I have fixed my problem.

Other than ensuring that I was binding my dialog and individual views to the same layout instance (and not different instances), I also needed to create a custom SpinnerAdapter for the BaseModel object as suggested here: https://stackoverflow.com/a/8116756/3438497

Hope this helps out anyone else facing this issue.

How to fill Android Spinner with object name from list

List<String> salutationList = new ArrayList<>();

salutationList.add("Title");
if (storage.getStorage() != null) {
for (storage.getStorage() data : storage.getStorage()) {
salutationList.add(data.getName());
}
}


Related Topics



Leave a reply



Submit