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

Android 元件開發:RatingBar 評分元件的用法

編輯:關於 Android 程式設計

RatingBar 是專門拿來做評分、評級的控制項,本質上是 SeekBar 的延伸,預設以星號呈現。使用上只要掛一個 OnRatingBarChangeListener 即可。

Java 端

public class MainActivity extends Activity {

    private RatingBar ratingBar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ratingBar = (RatingBar) findViewById(R.id.myRatingBar);
        ratingBar.setOnRatingBarChangeListener(new setRatingBarListener());
    }

    class setRatingBarListener implements RatingBar.OnRatingBarChangeListener {

        // 等級改變時呼叫
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
            System.out.println("RatingBar --->" + rating);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

布局檔

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/myText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <!-- numStars 表示有幾顆星;stepSize 表示每次移動前進幾顆星。
         寬度建議用 wrap_content,否則 numStars 只會被當成評分刻度,
         而不是實際顯示的星數 -->
    <RatingBar
        android:id="@+id/myRatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/myText"
        android:numStars="4"
        android:stepSize="0.5" />

</RelativeLayout>

幾個容易踩到的屬性

android:numStars 決定星數,設為 0 會變成連續的長條狀評分條。android:stepSize 決定每次變動的幅度,寫 0.5 就能做出半星效果,寫 1 則只能整顆。android:rating 可以在布局中直接指定初始值。

寬度那個細節值得留意:如果 layout_width 寫成 fill_parent 或明確數值,numStars 的意義會變成「在這個寬度內切幾等分」,星星的實際數量就不受控了。另外 RatingBar 預設是「不可取消」的——使用者點同一顆星不會回到 0,若需要這個行為,得自行在 onRatingChanged 中判斷並呼叫 setRating(0)。樣式方面也可以透過 style="?android:attr/ratingBarStyleSmall" 之類的內建樣式換外觀,或用 progressDrawable 自訂星圖。

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