Skip to content
The Chat Archive
claude-3-5-sonnet-20241022· Anthropic LMArena Human Preference 140K

在 Android 的自定义 View

  1. User

    在 Android 的自定义 View

  2. Assistant

    Android 自定义 View 是一个重要的主题,我来详细介绍一下:

    1. 自定义 View 的基本步骤:
    // 1. 继承 View 或其子类
    public class CustomView extends View {
        
        // 2. 实现构造方法
        public CustomView(Context context) {
            super(context);
            init();
        }
        
        public CustomView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(); 
        }
        
        // 3. 初始化
        private void init() {
            // 初始化画笔等
        }
        
        // 4. 重写 onMeasure 测量
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            // 设置宽高
            setMeasuredDimension(width, height);
        }
        
        // 5. 重写 onDraw 绘制
        @Override 
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            // 绘制内容
        }
    }
    
    1. 主要需要重写的方法:
    // 测量大小
    onMeasure()
    
    // 确定位置
    onLayout() 
    
    // 绘制
    onDraw()
    
    // 处理触摸事件
    onTouchEvent()
    
    1. 自定义属性:
    <!-- attrs.xml -->
    <declare-styleable name="CustomView">
        <attr name="custom_color" format="color" />
        <attr name="custom_size" format="dimension" />
    </declare-styleable>
    
    // 获取自定义属性
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
    int color = ta.getColor(R.styleable.CustomView_custom_color, defaultColor);
    float size = ta.getDimension(R.styleable.CustomView_custom_size, defaultSize);
    ta.recycle();
    
    1. 常用的绘制工具:
    // Paint 画笔
    Paint paint = new Paint();
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL); 
    paint.setStrokeWidth(5);
    
    // Canvas 画布
    canvas.drawCircle(x, y, radius, paint);
    canvas.drawRect(left, top, right, bottom, paint);
    canvas.drawText(text, x, y, paint);
    
    // Path 路径
    Path path = new Path();
    path.moveTo(x, y);
    path.lineTo(x1, y1);
    canvas.drawPath(path, paint);
    
    1. 事件处理:
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 按下
                break;
            case MotionEvent.ACTION_MOVE:
                // 移动
                break;
            case MotionEvent.ACTION_UP:
                // 抬起
                break;
        }
        return true;
    }
    
    1. 性能优化:
    // 避免在 onDraw 中创建对象
    private Paint mPaint;
    private Path mPath;
    
    private void init() {
        mPaint = new Paint();
        mPath = new Path();
    }
    
    // 使用 canvas.clipRect() 减少绘制区域
    canvas.clipRect(left, top, right, bottom);
    
    // 使用 canvas.quickReject() 判断是否需要绘制
    if (canvas.quickReject(left, top, right, bottom, Canvas.EdgeType.AA)) {
        return;
    }
    
    1. 常见使用场景:
    • 自定义进度条
    • 自定义图表
    • 自定义时钟
    • 自定义动画效果
    • 自定义手势交互
    1. 注意事项:
    • 合理使用 invalidate() 和 requestLayout()
    • 注意内存泄漏
    • 处理好 View 的生命周期
    • 注意绘制效率
    • 做好异常处理
    1. 示例 - 自定义进度条:
    public class CustomProgressBar extends View {
        private Paint mPaint;
        private int mProgress;
        private int mMax;
        
        public CustomProgressBar(Context context) {
            super(context);
            init();
        }
        
        private void init() {
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(10);
            mMax = 100;
        }
        
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            
            int width = getWidth();
            int height = getHeight();
            
            // 绘制背景
            mPaint.setColor(Color.GRAY);
            canvas.drawLine(0, height/2, width, height/2, mPaint);
            
            // 绘制进度
            mPaint.setColor(Color.BLUE);
            float progress = width * mProgress / mMax;
            canvas.drawLine(0, height/2, progress, height/2, mPaint);
        }
        
        public void setProgress(int progress) {
            mProgress = progress;
            invalidate();
        }
    }
    

    这些是自定义 View 的主要内容,掌握这些可以实现大多数自定义 View 的需求。在实际开发中,需要根据具体需求选择合适的实现方式。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.