How to create a view on an activity

android, android-activity

Solution

STEP 1: create a class by extends View as:

public class DrawView extends View {  
    public float currentX=40;  
    public float currentY=50;  

    public DrawView(Context context) {  
        super(context);  
        // TODO Auto-generated constructor stub  
    }  

    @Override  
    protected void onDraw(Canvas canvas) {        
        super.onDraw(canvas);   
        Paint paint=new Paint();  
        paint.setColor(Color.RED);  
        canvas.drawCircle(currentX, currentY, 25, paint);  
    }  

} 

STEP 2: In Your Stuff Activity :

public class Stuff extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);  
setContentView(R.layout.main);  
LinearLayout root=(LinearLayout) findViewById(R.id.root); 
(...)
}

@Override
public void onClick(View arg0) {
//DRAW YOUR VIEW ON BUTTON CLICK
final DrawView drawView=new DrawView(this);  
drawView.setMinimumWidth(300);  
drawView.setMinimumHeight(500);
drawView.currentX=200;  
drawView.currentY=200;  
drawView.invalidate(); 
root.addView(drawView);
(...)
}

STEP 3: Your Activity main.xml as :

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:orientation="vertical"   
    android:background="#99FFCC"  
    android:id="@+id/root">  
</LinearLayout>

and finally try to search on google before asking question here.thanks

Problem

So I have this class which extends an activity. But I want to draw something on the screen, so I need to make a canvas. However I can't extends View, because it's an activity allready. What should I do? My activity has the onClick method which I use to do some stuff, but what I wanna do is draw a simple image when I call the onClick method as well. Thanks. ``` public class Stuff extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { (...) } @Override public void onClick(View arg0) { (...) } ```

Original source