Search code examples
androidextend

I want to extend View from a Activity class


Currently I have a class called MapActivity that extends AppCompatActivity, and I need this because I have a acitivity_map.xml, but the thing is, I want to extend View, so that I can draw things on this activity.

How can I achive this ?


Solution

  • Recently i had the same question. Here is what i got: Create your own view:

    public class CustomView extends View
    

    Override the onDraw() method like this:

     @Override
        public void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.save();
            //draw something
            canvas.restore();
     }
    

    In your Activity in onCreate:

    setContentView(R.layout.activity_name);
        com.XXX.XXX.CustomView cV = (com.XXX.XXX.CustomView) findViewById(R.id.customView);
    

    And in the xml:

    <com.XXX.XXX.CustomView
            android:id="@+id/customView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />