Custom view -- Implement RatingBar and viewratingbar
First, let's take a look.
Stars are two different pictures.
First, the old routine: Custom Attributes
Customize RatingBar, draw two images, draw different images based on the location of getX, relatively simple direct paste source code
Public class RatingBar extends View {private Bitmap mStarNormalBitmap, mStarFocusBitmap; private int mGradeNumber = 5; private int mCurrentGrade = 0; public RatingBar (Context context) {this (context, null );} public RatingBar (Context context, AttributeSet attrs) {this (context, attrs, 0);} public RatingBar (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr ); TypedArray ta = context. obtainStyledAttributes (attrs, R. styleable. ratingBar); int starNormalId = ta. getResourceId (R. styleable. ratingBar_starNormal, 0); if (starNormalId = 0) {throw new RuntimeException ("set attribute starNormal");} mStarNormalBitmap = BitmapFactory. decodeResource (getResources (), starNormalId); int starFocusId = ta. getResourceId (R. styleable. ratingBar_starFocus, 0); if (starFocusId = = 0) {throw new RuntimeException ("set the attribute starFocus");} mStarFocusBitmap = BitmapFactory. decodeResource (getResources (), starFocusId); mGradeNumber = ta. getInt (R. styleable. ratingBar_gradeNumber, mGradeNumber); ta. recycle () ;}@ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super. onMeasure (widthMeasureSpec, heightMeasureSpec); int height = mStarFocusBitmap. getHeigh T (); int width = (mStarFocusBitmap. getWidth () + getPaddingLeft () * mGradeNumber; setMeasuredDimension (width, height) ;}@ Override protected void onDraw (Canvas canvas) {for (int I = 0; I <mGradeNumber; I ++) {int x = I * (mStarFocusBitmap. getWidth () + getPaddingLeft (); if (mCurrentGrade> I) {canvas. drawBitmap (mStarFocusBitmap, x, 0, null);} else {canvas. drawBitmap (mStarNormalBitmap, x, 0, null );}}} @ Override public boolean onTouchEvent (MotionEvent event) {switch (event. getAction () {// case MotionEvent. ACTION_DOWN: // press to minimize the call case MotionEvent of onDraw. ACTION_MOVE: // case MotionEvent. ACTION_UP: // lift to minimize the call float x = event of onDraw. getX (); // get the current score int currentGrade = (int) (x/mStarFocusBitmap. getWidth () + 1; // The current score if (currentGrade <0) {currentGrade = 0;} if (currentGrade> mGradeN Umber) {currentGrade = mGradeNumber;} if (currentGrade = mCurrentGrade) {return true; // consume the current event. Reduce invalidate} // then refresh and display mCurrentGrade = currentGrade; invalidate (); break;} return true; // consume the current event }}
Layout usage