Xamarin.Android RatingBar
A RatingBar is a UI widget that displays a rating from one to five stars. The user may select a rating by taping on a star
In this section, you'll create a widget that allows the user to provide a
rating, with the RatingBar
widget.
Creating a RatingBar
Open the Resource/layout/Main.axml file and add the
RatingBar
element (inside theLinearLayout
):<RatingBar android:id="@+id/ratingbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numStars="5" android:stepSize="1.0"/>
The
android:numStars
attribute defines how many stars to display for the rating bar. Theandroid:stepSize
attribute defines the granularity for each star (for example, a value of0.5
would allow half-star ratings).To do something when a new rating has been set, add the following code to the end of the
OnCreate()
method:RatingBar ratingbar = FindViewById<RatingBar>(Resource.Id.ratingbar); ratingbar.RatingBarChange += (o, e) => { Toast.MakeText(this, "New Rating: " + ratingbar.Rating.ToString (), ToastLength.Short).Show (); };
This captures the
RatingBar
widget from the layout withFindViewById
and then sets an event method then defines the action to perform when the user sets a rating. In this case, a simpleToast
message displays the new rating.Run the application.