自定义View--评分控件RatingBar

该文章详细介绍了如何在Android中创建一个自定义的RatingBar,包括设置自定义属性如星星图片、间距和数量,以及通过onMeasure()进行尺寸测量,onDraw()方法进行绘制,和onTouch()方法处理用户触摸交互,实现动态改变评分的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义View三部曲:onMeasure()\onDraw()\onTouch()

1.效果实现分析

    1.1 分析:

        1.刚进来初始化的样子,
        2.用户需要触摸,处理用户交互的部分(onTouch)

2.自定义属性

    两张图片资源、 评分的等级数量

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="RatingBar">
        <attr name="starPadding" format="dimension"/>
        <attr name="origin" format="reference"/>
        <attr name="change" format="reference"/>
        <attr name="starNumber" format="integer"/>
   </declare-styleable>
</resources>

3.使用属性

  <com.example.progress.RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@color/purple_200"
        app:starPadding="50dp"
        app:change="@drawable/star_final"
        app:origin="@drawable/star"
        app:starNumber="5" />

4.自定义View--获取、测量、绘制、触碰

        4.1 获取

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 typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatingBar);
        starNumber = typedArray.getInt(R.styleable.RatingBar_starNumber,starNumber);
        RatingBar_origin = typedArray.getResourceId(R.styleable.RatingBar_origin,RatingBar_origin);
        RatingBar_change = typedArray.getResourceId(R.styleable.RatingBar_change,RatingBar_change);
        starPadding  = typedArray.getDimensionPixelSize(R.styleable.RatingBar_starPadding,starPadding);
        if(RatingBar_origin == 0 || RatingBar_change == 0){
            throw  new RuntimeException("加星星");
        }

        RatingBar_origin_pic = BitmapFactory.decodeResource(getResources(),RatingBar_origin);
        RatingBar_change_pic = BitmapFactory.decodeResource(getResources(),RatingBar_change);
        typedArray.recycle();
    }

        4.2 测量

   @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width  = (RatingBar_origin_pic.getWidth()+10)*starNumber + starPadding*2;
        int height = RatingBar_origin_pic.getHeight();
        setMeasuredDimension(width,height);

    }

        4.3 绘制

    @Override
    protected void onDraw(Canvas canvas) {
        Log.d(TAG,"onDraw");
        for(int i = 0;i<starNumber;i++){
            int x = i*(RatingBar_origin_pic.getWidth()+10)+starPadding;
            if(mCurrentStarNum > i){
                canvas.drawBitmap(RatingBar_change_pic,x,0,null);
            }else{
                canvas.drawBitmap(RatingBar_origin_pic,x,0,null);
            }
        }
    }

        4.4 触摸

@Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_DOWN:
                float x = event.getX();
                int currentStarNum = (int) (x /(float)RatingBar_origin_pic.getWidth()+1);
                if(currentStarNum < 0){
                    currentStarNum = 0;
                }
                if(currentStarNum > starNumber){
                    currentStarNum = starNumber;
                }
                if(mCurrentStarNum == currentStarNum){
                    return true;
                }
                mCurrentStarNum = currentStarNum;
                invalidate();
        }
        return true;
    }

5.附件

        5.1 View

package com.example.progress;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

public class RatingBar extends View {

    private static final String TAG = "RatingBar";
    private int starNumber = 5;
    private int RatingBar_origin = 5;
    private int starPadding;
    private int RatingBar_change = 5;
    private Bitmap RatingBar_origin_pic,RatingBar_change_pic;
    private int mCurrentStarNum = 0;

    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 typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatingBar);
        starNumber = typedArray.getInt(R.styleable.RatingBar_starNumber,starNumber);
        RatingBar_origin = typedArray.getResourceId(R.styleable.RatingBar_origin,RatingBar_origin);
        RatingBar_change = typedArray.getResourceId(R.styleable.RatingBar_change,RatingBar_change);
        starPadding  = typedArray.getDimensionPixelSize(R.styleable.RatingBar_starPadding,starPadding);
        if(RatingBar_origin == 0 || RatingBar_change == 0){
            throw  new RuntimeException("加星星");
        }

        RatingBar_origin_pic = BitmapFactory.decodeResource(getResources(),RatingBar_origin);
        RatingBar_change_pic = BitmapFactory.decodeResource(getResources(),RatingBar_change);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width  = (RatingBar_origin_pic.getWidth()+10)*starNumber + starPadding*2;
        int height = RatingBar_origin_pic.getHeight();
        setMeasuredDimension(width,height);

    }


    @Override
    protected void onDraw(Canvas canvas) {
        Log.d(TAG,"onDraw");
        for(int i = 0;i<starNumber;i++){
            int x = i*(RatingBar_origin_pic.getWidth()+10)+starPadding;
            if(mCurrentStarNum > i){
                canvas.drawBitmap(RatingBar_change_pic,x,0,null);
            }else{
                canvas.drawBitmap(RatingBar_origin_pic,x,0,null);
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_DOWN:
                float x = event.getX();
                int currentStarNum = (int) (x /(float)RatingBar_origin_pic.getWidth()+1);
                if(currentStarNum < 0){
                    currentStarNum = 0;
                }
                if(currentStarNum > starNumber){
                    currentStarNum = starNumber;
                }
                if(mCurrentStarNum == currentStarNum){
                    return true;
                }
                mCurrentStarNum = currentStarNum;
                invalidate();
        }
        return true;
    }

}

        5.2 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.progress.RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@color/purple_200"
        app:starPadding="50dp"
        app:change="@drawable/star_final"
        app:origin="@drawable/star"
        app:starNumber="5" />
	</LinearLayout>

        5.3 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.progress">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MVC">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Abednego_子瑜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值