Android自定義View仿大眾點評星星評分控件

本文實例為大傢分享瞭Android仿大眾點評星星評分控件的具體代碼,供大傢參考,具體內容如下

話不多說,直接上代碼,這裡采用的是自定View

public class RatingBar extends View {
 // 正常、半個和選中的星星
 private Bitmap mStarNormal, mStarHalf, mStarSelected;
 //星星的總數
 private int mStartTotalNumber = 5;
 //選中的星星個數
 private float mSelectedNumber;
 // 星星之間的間距
 private int mStartDistance;
 // 是否畫滿
 private Status mStatus = Status.FULL;
 // 星星的寬高
 private float mStarWidth;
 private float mStarHeight;
 // 星星選擇變化的回調
 private OnStarChangeListener mOnStarChangeListener;
 // 是不是要畫滿,默認不畫半個的
 private boolean isFull;
 // 畫筆
 private Paint mPaint = new Paint();
 // 用於判斷是繪制半個,還是全部
 private enum Status {
  FULL, HALF
 }
 public void setOnStarChangeListener(OnStarChangeListener OnStarChangeListener) {
  this.mOnStarChangeListener = OnStarChangeListener;
 }
 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);
  TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RatingBar);

  // 未選中的圖片資源
  int starNormalId = array.getResourceId(R.styleable.RatingBar_starEmptyRes, 0);
  if (starNormalId == 0) {
   throw new IllegalArgumentException("請設置屬性 starNormal");
  }
  mStarNormal = BitmapFactory.decodeResource(getResources(), starNormalId);
  // 選中一半的圖片資源
  int starHalfId = array.getResourceId(R.styleable.RatingBar_starHalfRes, 0);
  if (starHalfId != 0) {
   mStarHalf = BitmapFactory.decodeResource(getResources(), starHalfId);
  }
  // 選中全部的圖片資源
  int starSelectedId = array.getResourceId(R.styleable.RatingBar_starSelectedRes, 0);
  if (starSelectedId == 0) {
   throw new IllegalArgumentException("請設置屬性 starSelected");
  }
  mStarSelected = BitmapFactory.decodeResource(getResources(), starSelectedId);
  // 如果沒設置一半的圖片資源,就用全部的代替
  if (starHalfId == 0) {
   mStarHalf = mStarSelected;
  }

  mStartTotalNumber = array.getInt(R.styleable.RatingBar_startTotalNumber, mStartTotalNumber);
  mSelectedNumber = array.getFloat(R.styleable.RatingBar_selectedNumber, mSelectedNumber);
  mStartDistance = (int) array.getDimension(R.styleable.RatingBar_starDistance, 0);
  mStarWidth = array.getDimension(R.styleable.RatingBar_starWidth, 0);
  mStarHeight = array.getDimension(R.styleable.RatingBar_starHeight, 0);
  isFull = array.getBoolean(R.styleable.RatingBar_starIsFull, true);
  array.recycle();

  // 如有指定寬高,獲取最大值 去改變星星的大小(星星是正方形)
  int starWidth = (int) Math.max(mStarWidth, mStarHeight);
  if (starWidth > 0) {
   mStarNormal = resetBitmap(mStarNormal, starWidth);
   mStarSelected = resetBitmap(mStarSelected, starWidth);
   mStarHalf = resetBitmap(mStarHalf, starWidth);
  }
  // 計算一半還是全部(小數部分小於等於0.5就隻是顯示一半)
  if (!isFull) {
   int num = (int) mSelectedNumber;
   if (mSelectedNumber <= (num + 0.5f)) {
    mStatus = Status.HALF;
   }
  }
 }

 /**
  * 設置全部選中的圖片
  *
  * @param bitmap
  */
 public void allImage(Bitmap bitmap) {
  mStarSelected = bitmap;
  int starWidth = (int) Math.max(mStarWidth, mStarHeight);
  if (starWidth > 0) {
   mStarNormal = resetBitmap(mStarNormal, starWidth);
   mStarSelected = resetBitmap(mStarSelected, starWidth);
   mStarHalf = resetBitmap(mStarHalf, starWidth);
  }
  invalidate();
 }

 /**
  * 設置選中一半的圖片
  *
  * @param bitmap
  */
 public void mStarHalf(Bitmap bitmap) {
  mStarHalf = bitmap;
  int starWidth = (int) Math.max(mStarWidth, mStarHeight);
  if (starWidth > 0) {
   mStarNormal = resetBitmap(mStarNormal, starWidth);
   mStarSelected = resetBitmap(mStarSelected, starWidth);
   mStarHalf = resetBitmap(mStarHalf, starWidth);
  }
  invalidate();
 }

 /**
  * 如果用戶設置瞭圖片的寬高,就重新設置圖片
  */
 public Bitmap resetBitmap(Bitmap bitMap, int startWidth) {
  // 得到新的圖片
  return Bitmap.createScaledBitmap(bitMap, startWidth, startWidth, true);
 }

 /**
  * 設置選中星星的數量
  */
 public void setSelectedNumber(int selectedNumber) {
  if (selectedNumber >= 0 && selectedNumber <= mStartTotalNumber) {
   this.mSelectedNumber = selectedNumber;
   invalidate();
  }
 }

 /**
  * 設置星星的總數量
  */
 public void setStartTotalNumber(int startTotalNumber) {
  if (startTotalNumber > 0) {
   this.mStartTotalNumber = startTotalNumber;
   invalidate();
  }
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  // 用正常的一個星星圖片去測量高
  int height = getPaddingTop() + getPaddingBottom() + mStarNormal.getHeight();
  // 寬 = 星星的寬度*總數 + 星星的間距*(總數-1) +padding
  int width = getPaddingLeft() + getPaddingRight() + mStarNormal.getWidth() * mStartTotalNumber + mStartDistance * (mStartTotalNumber - 1);
  setMeasuredDimension(width, height);
 }

 @Override
 protected void onDraw(Canvas canvas) {
  // 循環繪制
  for (int i = 0; i < mStartTotalNumber; i++) {
   float left = getPaddingLeft();
   // 從第二個星星開始,給它設置星星的間距
   if (i > 0) {
    left = getPaddingLeft() + i * (mStarNormal.getWidth() + mStartDistance);
   }
   float top = getPaddingTop();
   // 繪制選中的星星
   if (i < mSelectedNumber) {
    // 比當前選中的數量小
    if (i < mSelectedNumber - 1) {
     canvas.drawBitmap(mStarSelected, left, top, mPaint);
    } else {
     // 在這裡判斷是不是要繪制滿的
     if (mStatus == Status.FULL) {
      canvas.drawBitmap(mStarSelected, left, top, mPaint);
     } else {
      canvas.drawBitmap(mStarHalf, left, top, mPaint);
     }
    }
   } else {
    // 繪制正常的星星
    canvas.drawBitmap(mStarNormal, left, top, mPaint);
   }
  }
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  switch (event.getAction()) {
   //減少繪制
   case MotionEvent.ACTION_MOVE:
    // 獲取用戶觸摸的x位置
    float x = event.getX();
    // 一個星星占的寬度
    int startWidth = getWidth() / mStartTotalNumber;
    // 計算用戶觸摸星星的位置
    int position = (int) (x / startWidth + 1);
    if (position < 0) {
     position = 0;
    }
    if (position > mStartTotalNumber) {
     position = mStartTotalNumber;
    }
    // 計算繪制的星星是不是滿的
    float result = x - startWidth * (position - 1);
    Status status;
    // 結果大於一半就是滿的
    if (result > startWidth * 0.5f) {
     // 滿的
     status = Status.FULL;
    } else {
     // 一半的
     status = Status.HALF;
    }
    if (isFull) {
     status = Status.FULL;
    }
    //減少繪制
    if (mSelectedNumber != position || status != mStatus) {
     mSelectedNumber = position;
     mStatus = status;
     invalidate();
     if (mOnStarChangeListener != null) {
      position = (int) (mSelectedNumber - 1);
      // 選中的數量:滿的就回調(1.0這種),一半就(0.5這種)
      float selectedNumber = status == Status.FULL ? mSelectedNumber
        : (mSelectedNumber - 0.5f);
      mOnStarChangeListener.OnStarChanged(selectedNumber,
        position < 0 ? 0 : position);
     }
    }
    break;
  }
  return true;
 }

 // 回調監聽(選中的數量,位置)
 public interface OnStarChangeListener {
  void OnStarChanged(float selectedNumber, int position);
 }
}

自定義屬性

<declare-styleable name="RatingBar">
  <!--未選中-->
  <attr name="starEmptyRes" format="reference" />
  <!--選中半個-->
  <attr name="starHalfRes" format="reference" />
  <!--選中全部-->
  <attr name="starSelectedRes" format="reference" />
  <!--星星的總數-->
  <attr name="startTotalNumber" format="integer" />
  <!--默認選中的數量 -->
  <attr name="selectedNumber" format="float" />
  <!--星星的間距-->
  <attr name="starDistance" format="dimension" />
  <!--星星的寬度-->
  <attr name="starWidth" format="dimension" />
  <!--星星的高度-->
  <attr name="starHeight" format="dimension" />
  <!--是不是隻畫整個星星,不畫半個-->
  <attr name="starIsFull" format="boolean" />
</declare-styleable>

xml 配置

<com.demo.mvp_demo.ui.shop.RatingBar
  android:id="@+id/rb"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_gravity="center"
  app:starHeight="30dp"
  app:starWidth="30dp"
  app:selectedNumber="0.0"
  app:starDistance="15dp"
  app:starEmptyRes="@drawable/no"
  app:starHalfRes="@drawable/twoban"
  app:starIsFull="false"
  app:starSelectedRes="@drawable/two" />

在activity裡 rb指的是 RatingBar rb;

大概就是這個樣子 具體的需求 需要根據UI提供圖來.

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: