user2789240
user2789240

Reputation: 97

Android: How do I separate it into 2 class?

I read a tutorial online about drawing a Circle (1st part of tutorial): Introduction to 2D drawing in Android with example

I got it worked. Now I want to separate them into 2 classes:

MainActivity.java

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(new SimpleView(this));

    }

}

SimpleView.java

public class SimpleView extends SurfaceView {

public SimpleView(Context context) {

    super(context);
}

@Override
protected void onDraw(Canvas canvas) {

    super.onDraw(canvas);
    int x = getWidth();
    int y = getHeight();
    int radius;
    radius = 100;
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.GREEN);
    canvas.drawPaint(paint);
    // Use Color.parseColor to define HTML colors
    paint.setColor(Color.parseColor("#CD5C5C"));
    canvas.drawCircle(x / 2, y / 2, radius, paint);

}

}

However, I wasn't able to get them work: it never draws anything.

What did I do wrong here?

Upvotes: 1

Views: 34

Answers (1)

Leo
Leo

Reputation: 844

If you want to use a SurfaceView you can, all you need to do is to call setWillNotDraw(false) on the constructor so the class will look like this:

public class SimpleView extends SurfaceView {

    public SimpleView(Context ctx) {
        super(ctx);
        setWillNotDraw(false); //notice this method call IMPORTANT
    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);
        int x = getWidth();
        int y = getHeight();
        int radius;
        radius = 100;
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.GREEN);
        canvas.drawPaint(paint);
        // Use Color.parseColor to define HTML colors
        paint.setColor(Color.parseColor("#CD5C5C"));
        canvas.drawCircle(x / 2, y / 2, radius, paint);


    }
}

Upvotes: 2

Related Questions