栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android自定义View实现五星好评效果

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android自定义View实现五星好评效果

本文实例为大家分享了Android实现五星好评效果的具体代码,供大家参考,具体内容如下

这个效果想必大家都非常熟悉,那么Android如何自定义实现这种效果呢?

首先自定义属性:



  
    
    
    
  

下面看看具体实现:


 
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 < 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;
  }
}

最后看看具体布局中使用:

 

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/154691.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号