Android:如何将其分为2个类?

时间:2016-03-24 19:17:44

标签: android

我在线阅读了关于绘制圆形的教程(教程的第1部分): Introduction to 2D drawing in Android with example

我明白了。现在我想将它们分成两类:

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);

}

}

但是,我无法让它们发挥作用:它从不吸引任何东西。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

如果你想使用SurfaceView,你需要做的就是在构造函数上调用setWillNotDraw(false),这样类就像这样:

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);


    }
}