Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發實戰:RatingBar 評分控件用法全解析

編輯:關於 Android 程式設計

在電商、音樂、影片這類應用裡,「打分」幾乎是標配的互動。Android 為此提供了現成的 RatingBar 控件,它以一排星星的形式呈現,用戶點擊或拖動即可給出評價,開發者則可以透過監聽器即時拿到分數。

一、RatingBar 常用方法速查

  • setMax():設定評分項目的最大值,也就是滿分是多少。
  • setNumStars():設定星星的個數。這裡有個容易踩的坑——控件的布局寬度必須寫成 wrap_content,一旦寫成 fill_parent,實際顯示的星星數量很可能與你設定的值不符。
  • setRating():設定當前分數,同時它也會影響星星的填充狀態。
  • setStepSize():設定每次變動的最小步長。例如 setStepSize(0.5f) 表示最小只能以半顆星為單位調整。
  • setOnRatingBarChangeListener():註冊監聽器,用戶分數發生變化時回呼 onRatingChanged()。

二、完整示例

MainActivity.java:

public class MainActivity extends Activity {
    private RatingBar bar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bar = (RatingBar) findViewById(R.id.rat);
        bar.setNumStars(5);        // 五顆星
        bar.setMax(100);           // 滿分 100
        bar.setRating(1.5f);       // 初始 1.5 分
        bar.setStepSize(0.5f);     // 最小步長半顆星

        bar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                Toast.makeText(MainActivity.this, "當前得分:" + rating * 20,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

activity_main.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}">

    <RatingBar
        android:id="@+id/rat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

運行效果如下:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved