Android: How to use the onDraw method in a class extending Activity?

淺唱寂寞╮ 提交于 2019-12-01 05:07:10

Simple example using onDraw function-it requires class to extend view

Context to get the current activity context

public class MainActivity extends Activity {

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

    setContentView(new myview(this));


}

class myview extends View
{

    public myview(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }
    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        int x=80;
        int y=80;
        int radius=40;
        Paint paint=new Paint();
        // Use Color.parseColor to define HTML colors
        paint.setColor(Color.parseColor("#CD5C5C"));
        canvas.drawCircle(x,x, radius, paint);
    }

}

}

I think that you cant use onDraw in class extending an Activity because of using Canvas, you need to create a Custom component extending some View and there handle you action,and what do you need to do that=>

1.Extend an existing View class or subclass with your own class.

2.Override some of the methods from the superclass. The superclass methods to override start with ‘on’, for example,onDraw(), onMeasure(), onKeyDown(). This is similar to the‘on’ events in Activity that you override for lifecycle and other functionality hooks.

3.Use your new extension class. Once completed, your new extension class can be used in place of the view upon which it was based.

Couldn't you just place an ImageView next to your counter? You could do that in your xml layout file:

<ImageView
    android:id="@id+/my_image"
    android:layout_width="50dip"
    android:layout_height="50dip"
    android:src="@drawable/name_of_my_image" />

Or in your acrivity:

@Override
protected void onCreate(Bundle bundle) {
    // ...
    ImageView image = (ImageView) findViewById(R.id.my_image);
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
    image.setImageBitmap(bitmap);
}

If you want to use a custom view and override the onDraw() method here's what you need to do:

class MyCustomView extends View {
    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // your custom drawing
        canvas.drawRect(0, 0, 50, 50, new Paint());
    }
}

For any doubt, you can refer to Android Training

Gagandeep

You don't need to use View.onDraw() for this purpose. Just use layouts and place any drawable image next to your counter, let's say a textview, using the drawableLeft attribute.

txtview_counter.drawableLeft="@drawable/xxx"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!