重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章将为大家详细讲解有关Android中怎么通过自定义View实现五星好评效果,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
创新互联长期为1000多家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为叠彩企业提供专业的成都做网站、成都网站建设,叠彩网站改版等技术服务。拥有十年丰富建站经验和众多成功案例,为您定制开发。
首先自定义属性:
下面看看具体实现:
/** * 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 h2; 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(); h2 = normalImg.getHeight(); //中间间隔 p = 30; marginTop = 20; marginBottom = 20; marginLeft = 20; marginRight = 20; height = h2 + 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 < number; i++) { if (i <= i0){ canvas.drawBitmap(focusImg,i*w1+marginLeft+i*p,marginTop,null); mGrade = i+1; }else{ canvas.drawBitmap(normalImg,i*w1+marginLeft+i*p,marginTop,null); } } Log.e("msg","我被调用了!"); } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX();//相对于控件自身的距离 //event.getRawX() 相对于屏幕的距离 switch (event.getAction()){ case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: //case MotionEvent.ACTION_UP: w0 = getWidth()/5; i0 = (int) (x/w0); //性能优化,减少onDraw()调用 if (mGrade == i0+1){ return true; } invalidate(); break; } return true; }}
最后看看具体布局中使用:
关于Android中怎么通过自定义View实现五星好评效果就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。