Populate spinner with custom object

巧了我就是萌 提交于 2020-02-05 06:25:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!