關鍵是把 progressDrawable 指向自訂的 drawable,再配合 numStars 與 stepSize 控制星數與最小刻度。
<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"
tools:context="${relativePackage}.${activityClass}" >
<RatingBar
android:id="@+id/rb"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:numStars="5"
android:progressDrawable="@drawable/rating_star"
android:stepSize="0.5" />
<TextView
android:id="@+id/tv_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rb"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:text="當前評分是:" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rb"
android:layout_marginTop="20dp"
android:layout_toRightOf="@id/tv_num"
android:text="0.0"
android:textColor="#FF0000" />
</RelativeLayout>
這裡 stepSize 設為 0.5,代表可以打半顆星;rating_star 則是放在 res/drawable 下的自訂樣式資源。
package com.example.ratingbar;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv;
private RatingBar rb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
rb = (RatingBar) findViewById(R.id.rb);
rb.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
if (fromUser) {
tv.setText(Float.toString(rating));
}
}
});
}
}
這裡有個容易忽略的細節:fromUser 參數用來判斷分數變更是來自使用者操作還是程式設定。加上這個判斷,可以避免程式初始設定分數時觸發回呼,導致顯示值被意外覆寫。
