我的自定义视图无法添加到xml

时间:2017-03-13 14:31:47

标签: android xml view

我尝试通过扩展View类创建自己的自定义视图,它只使用java代码工作正常, 但当我尝试将其添加到xml时,我的应用程序崩溃了。

所以我希望有人能帮助我。 这是我的代码和xml.

当前代码

package com.miller.ian.drawcanvas;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;

/**
 * Created by Ian on 3/13/2017.
 */

public class MyView extends View{
    private class Size {
        private int x;
        private int y;
        private Size(){
            this(0,0);
        }
        private Size(int x,int y){
            this.x = x;
            this.y = y;
        }
    }

    private int count = 0;
    private Size size;
    private RectF rectf;
    private Paint paint = new Paint();
    public MyView(Context context, int x, int y){
        super(context);
        size = new Size(x,y);
        paint.setStyle(Paint.Style.FILL);
        rectf = new RectF(size.x/3,size.y/3,2*size.x/3,2*size.y/3);
        this.setOnClickListener(new View.OnClickListener() {
           @Override
            public void onClick(View v) {
                switch (count%3) {
                    case 0:
                        v.setBackgroundColor(Color.BLUE);
                        break;
                    case 1:
                        v.setBackgroundColor(Color.YELLOW);
                        break;
                    case 2:
                        v.setBackgroundColor(Color.GREEN);
                    default:
                }
                count++;
            }
        });
    }
    @Override
    protected void onDraw(Canvas canvas){
        canvas.drawRoundRect(rectf,size.x/9,size.y/9,paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        this.setMeasuredDimension(size.x,size.y);
    }


}

当前xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/view_group"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.miller.ian.drawcanvas.MainActivity">

    <com.miller.ian.drawcanvas.MyView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    </LinearLayout>

0 个答案:

没有答案