自定义RatingBar(自适应宽高)

【自定义RatingBar(自适应宽高)】解决官方RatingBar无法自由调整宽高的问题
可选则适应宽度或者高度
自定义RatingBar(自适应宽高)
文章图片
MyRatingBar.gif 红色背景为自适应后的宽高
在values下创建attrs文件
只设置了常用的
step 步距
rating 当前星值
starts 星星总数
以及可选则适应宽度或者高度 base_of_width_or_height
并添加


代码部分
public class MyRatingBar extends View { private Context context; private int width; //设置高 private int height; //设置高private Paint paint; //星星总数 private int starSum=3; //当前星星数 private float rating=3; //每步间隔 private float step=0.1f; //每步距离 private float stepWidth=0; //每个星星宽度 private int starWidth=0; //适应宽高度(0:宽度,1:高度) private int width_height=0; public MyRatingBar(Context context) { super(context); this.context=context; initPaint(); }public MyRatingBar(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context,attrs); this.context=context; initPaint(); }public MyRatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context=context; initPaint(); }private void init(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyRatingBar); starSum=a.getInt(R.styleable.MyRatingBar_stars,5); step=a.getFloat(R.styleable.MyRatingBar_step,1f); width_height=a.getInt(R.styleable.MyRatingBar_base_of_width_or_height, 0); rating=a.getFloat(R.styleable.MyRatingBar_rating,starSum); }@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawBackgroundStars(canvas); drawStars(canvas); }/** * 背景 * @param canvas */ private void drawBackgroundStars(Canvas canvas) { Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.icon_star_gray_128)).getBitmap(); for (int i = 0; i < starSum; i++) { canvas.drawBitmap(bitmap,new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()),new Rect(starWidth*i,0,starWidth*(i+1),starWidth),paint); } }/** * 星星 * @param canvas */ private void drawStars(Canvas canvas) { Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.icon_star_yellow_128)).getBitmap(); stepWidth=step*starWidth; int stepNum=(int)(currentX/stepWidth); rating=round((double)stepNum*step,2); for (int i = 0; i < stepNum*stepWidth/starWidth; i++) { int leftX=starWidth*i; int rightX=starWidth*(i+1); int x=(int)(stepNum*stepWidth-starWidth*i); if(currentX>leftX&¤tX=0&&event.getX()<=width){ currentX=event.getX()+stepWidth/2; }else if(event.getX()<0){ currentX=stepWidth/2; }else if(event.getX()>width){ currentX=width+stepWidth/2; } invalidate(); break; } return super.onTouchEvent(event); }public int getStarSum() { return starSum; }public void setStarSum(int starSum) { this.starSum = starSum; invalidate(); }public float getRating() { return rating; }public void setRating(float rating) { this.rating = rating; invalidate(); }public float getStep() { return step; }public void setStep(float step) { this.step = step; invalidate(); } }

使用:
根布局中添加
xmlns:app="http://schemas.android.com/apk/res-auto"


GitHub地址 https://github.com/zjd77065163/MyRatingBar

    推荐阅读