您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關怎么在Android中通過自定義View實現一個五星好評效果,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
首先自定義屬性:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="RatingStar"> <attr name="starNormal" format="reference"/> <attr name="starFocus" format="reference"/> <attr name="starNumber" format="integer"/> </declare-styleable> </resources>
下面看看具體實現:
/** * 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; } }
最后看看具體布局中使用:
<com.example.star.RatingStar android:layout_width="wrap_content" android:layout_height="wrap_content" app:starNormal="@mipmap/star_normal" app:starFocus="@mipmap/star_selected" app:starNumber="5" />
上述就是小編為大家分享的怎么在Android中通過自定義View實現一個五星好評效果了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。