Android: How can you set the value of a ratingBar within a ListAdapter?
I'm trying to figure out how to set the value of a ratingBar that is in a list, but haven't been able to figure it out.
I'm currently using a simple adapter to set the text.
Where mylist is a hashmap.
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list_simple,
new String[] { "name"},
new int[] { R.id.item_title});
setListAdapter(adapter);
And my xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="@color/white">
<TextView
style="@style/ListHeading"
android:id="@+id/item_title"
android:gr开发者_StackOverflow中文版avity="left"/>
<RatingBar
style="@style/RatingBarSm"
android:id="@+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:isIndicator="true"/>
</LinearLayout>
When I try to add "rating" to the simple adapter, I get this error.
ERROR/AndroidRuntime(10793): java.lang.IllegalStateException: android.widget.RatingBar is not a view that can be bounds by this SimpleAdapter
I haven't been able to find anything useful on this. Any help or direction is greatly appreciated.
You can use SimpleAdapter.ViewBinder as a private class within the activity
class MyBinder implements ViewBinder{
@Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if(view.getId() == R.id.ratingBar){
String stringval = (String) data;
float ratingValue = Float.parseFloat(stringval);
RatingBar ratingBar = (RatingBar) view;
ratingBar.setRating(ratingValue);
return true;
}
return false;
}
}
Then you can set the ViewBinder to the SimpleAdapter in the following manner.
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list_simple,
new String[] { "name", "rating"},
new int[] { R.id.item_title, R.id.ratingBar});
adapter.setViewBinder(new MyBinder());
setListAdapter(adapter);
Binding data to views occurs in two phases. First, if a SimpleAdapter.ViewBinder
is available, setViewValue(android.view.View, Object, String)
is invoked. If the returned value is true, binding has occurred. If the returned value is false, the views are then tried by SimpleAdapter in order.
For more info on this you can browse the SimpleAdapter
I guess we need not create a custom list adapter.
精彩评论