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

前端 未结 4 1937
离开以前
离开以前 2021-01-11 17:31

As a beginner, I\'ve been building a simple counter application using a simple layout xml and a class called \'Counter\', which derives (extends) from the class Activity.

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 17:49

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

    
    

    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

提交回复
热议问题