本文实例为大家分享了Android实现五星好评效果的具体代码,供大家参考,具体内容如下
这个效果想必大家都非常熟悉,那么Android如何自定义实现这种效果呢?
首先自定义属性:
<&#63;xml version="1.0" encoding="utf-8"&#63;>
下面看看具体实现:
/** * Created by Michael on 2019/11/1. */ public class RatingStar extends View { private int normalId; private int focusId; private Bitmap normalImg; private Bitmap focusImg; private int number; private int w1; private int h1; private int marginLeft; private int marginTop; private int marginBottom; private int marginRight; private int height; private int width; private int p; private float w0; private int i0; private int mGrade; public RatingStar(Context context) { this(context,null); } public RatingStar(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public RatingStar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.RatingStar); normalId = array.getResourceId(R.styleable.RatingStar_starNormal,0); focusId = array.getResourceId(R.styleable.RatingStar_starFocus,0); normalImg = BitmapFactory.decodeResource(getResources(), normalId); focusImg = BitmapFactory.decodeResource(getResources(), focusId); number = array.getInteger(R.styleable.RatingStar_starNumber,5); array.recycle(); i0 = -1; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { w1 = normalImg.getWidth(); h1 = normalImg.getHeight(); //中间间隔 p = 30; marginTop = 20; marginBottom = 20; marginLeft = 20; marginRight = 20; height = h1 + marginTop + marginBottom; width = w1 *number+(number-1)*p +marginLeft+marginRight; setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i
最后看看具体布局中使用:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。