Xamarin RatingBarXamarin.Android RatingBar

RatingBar 是一个 UI 小组件,用于显示一到五个星的分级。A RatingBar is a UI widget that displays a rating from one to five stars. 用户可在本部分中的星形上选择分级轻按,你将创建一个小组件,以允许用户使用RatingBar小组件提供评级。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.

RatingBar 的示例

创建 RatingBarCreating a RatingBar

  1. 打开Resource/layout/main.axml文件并添加RatingBarOpen the Resource/layout/Main.axml file and add the RatingBar 元素(在LinearLayout内):element (inside the LinearLayout):

    <RatingBar android:id="@+id/ratingbar"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:numStars="5"
             android:stepSize="1.0"/>
    

    android:numStars 属性定义要为分级栏显示多少星。The android:numStars attribute defines how many stars to display for the rating bar. android:stepSize 属性定义每个星形的粒度(例如,值 0.5 将允许使用半星级别)。The android:stepSize attribute defines the granularity for each star (for example, a value of 0.5 would allow half-star ratings).

  2. 若要在设置新分级时执行某些操作,请将以下代码添加到OnCreate()的末尾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 ();
    };
    

    这会从具有FindViewById的布局捕获RatingBar小组件,然后设置事件方法,并定义在用户设置分级时要执行的操作。This captures the RatingBar widget from the layout with FindViewById and then sets an event method then defines the action to perform when the user sets a rating. 在这种情况下,简单的Toast消息会显示新级别。In this case, a simple Toast message displays the new rating.

  3. 运行该应用程序。Run the application.