TAGS :Viewed: 20 - Published at: a few seconds ago

[ Add RatingBar into ListFragment dynamically ]

I have a ListFragment which only includes the ListView I want to populate dynamically. The problem is I want to fill it with RatingBar views. What I do is declare a RatingBar and then adding it to the View.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    RatingBar rb = new RatingBar(this.getActivity());
    rb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

    getListView().addView(rb);

    return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
}

and I get the error:

java.lang.IllegalStateException: Content view not yet created

How can I add a RatingBar in each ListView line which is inside a ListFragment?

EDIT: okay so I changed my code to this:

RatingBar rb = new RatingBar(getActivity());
rb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
                   LayoutParams.WRAP_CONTENT));
rb.setIsIndicator(true);
rb.setNumStars(5);

List<RatingBar> lrb =  new ArrayList<RatingBar>();

for (int i = 0; i < li.size(); i++)
    lrb.add(rb);

setListAdapter(new ArrayAdapter<RatingBar>(this.getActivity(),
               android.R.layout.simple_selectable_list_item, lrb));

But although I'm not getting the error I get these results:

Emulator Results

Answer 1


ArrayAdapter is not really convenient to display more than simple 'TextViews'. You have to create you own adapter, probably by derivating from a simple BaseAdapter. Then you have to fill you adapter with your data. It will update the list view with the correct views. You can have a look a this tutorial.