How do I call onDraw after setContentView (R.layout.main)?
I need to draw something at runtime. I have been drawing inDraw in the MyView class. Because I have already used setContentView (R.layout.main) in onCreate, I cannot use it again.
How can I call onDraw after setContentView (R.layout.main)?
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // I have something to draw in XML also.
MyView myView = new MyView(this);
// setContentView(myView); I cannot use setContentView two times.
}
protected class MyView extends View {
public MyView(Context context) {
super(context);
}
public void onDraw(Canvas canvas) {
// there are some drawing codes and these cannot be done in XML.
}
}
source to share
I see two paths
1: You can add myView (instance) to the ViewGroup defined in R.layout.main
2: You can directly add MyView to your XML R.layout.main. Instead of "LinearLayout" etc. You get the fully qualified class name
see http://developer.android.com/guide/topics/ui/custom-components.html (at bottom)
source to share
You don't have to call onDraw () yourself. Instead, to force redrawing, call invalidate()
.
If the view is visible, it
onDraw(android.graphics.Canvas)
will be at some point in the future.
source to share
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);
MakeView makeView = new MakeView(this);
relativeLayout.addView(makeView);
relativeLayout.invalidate();
}
I noticed that onDraw is called after addView.
source to share