Android自定义Rating Bar
一、效果图

二、代码实现
package com.example.layoutdemo.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import com.example.layoutdemo.R;
public class RatingBar extends View {
private Bitmap mNormalStar;
private Bitmap mSelectedStar;
private int mCurrentStep = 0;
private static final int NUM = 5;
public RatingBar(Context context) {
this(context,null);
}
public RatingBar(Context context, @Nullable AttributeSet attrs) {
this(context,attrs,0);
}
public RatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mNormalStar = BitmapFactory.decodeResource(context.getResources(), R.mipmap.star_normal);
mSelectedStar = BitmapFactory.decodeResource(context.getResources(),R.mipmap.star_selected);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(mNormalStar.getWidth() * NUM,mNormalStar.getHeight());
}
@Override
protected void onDraw(Canvas canvas) {
for (int i = 0;i <= NUM;i++) {
if (mCurrentStep > i) {
canvas.drawBitmap(mSelectedStar,i * mSelectedStar.getWidth(),0,null);
} else {
canvas.drawBitmap(mNormalStar,i * mNormalStar.getWidth(),0,null);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("TAG","MotionEvent.ACTION_DOWN");
case MotionEvent.ACTION_MOVE:
int currentStep = (int)(event.getX()/mNormalStar.getWidth() + 1);
Log.d("TAG","currentStep:" + currentStep);
if (currentStep < 0) {
mCurrentStep = 0;
}
if (currentStep >NUM) {
mCurrentStep = NUM;
}
if (currentStep == mCurrentStep) {
return true;
}
mCurrentStep = currentStep;
invalidate();
break;
case MotionEvent.ACTION_UP:
Log.d("TAG","MotionEvent.ACTION_UP");
break;
}
return true;
}
}
三、使用控件
<com.example.layoutdemo.widget.RatingBar
android:layout_marginStart="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
四、源码下载地址
Android自定义View