通过自定义RatingBar的样式实现⭐️⭐️⭐️指示器的方式功能过于受限,而且显示的样式阴影会受到影响。
系统自带显示:
自定义样式:
因此简单自一个符合要求的 CustomRatingBar
- 支持设置星星数量
- 支持设置星星Rating(float)
- 支持设置空显示
- 支持设置半空显示
- 支持设置全显示
- 支持设置星星之间的间距
- 支持设置星星的宽高
1. 创建自定义 RatingBar 类
首先,创建一个自定义的 RatingBar 类,继承自 View,并重写相关方法。
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.example.yourapp.R
class CustomRatingBar @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private var starCount = 5 // 星星数量
private var rating = 0f // 当前评分
private var starSpacing = 0 // 星星间距
private var starWidth = 0 // 星星宽度
private var starHeight = 0 // 星星高度
private var starEmptyDrawable: Drawable? = null
private var starHalfDrawable: Drawable? = null
private var starFullDrawable: Drawable? = null
init {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.CustomRatingBar, 0, 0)
try {
starCount = a.getInteger(R.styleable.CustomRatingBar_starCount, starCount)
rating = a.getFloat(R.styleable.CustomRatingBar_rating