I tried to create my own custom view by extending View class , it worked fine with only java code, but when I tried to add it to xml, my app crashed.
So I hope anyone can help me.
Here's my code and xml.
Current code:
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);
}
}
Current 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>