I have a class Drawview:
public class DrawView extends View {
private ColorBall[] colorballs = new ColorBall[3]; // array that holds the balls
private int balID = 0; // variable to know what ball is being dragged
public DrawView(Context context) {
super(context);
setFocusable(true); //necessary for getting the touch events
// setting the start point for the balls
Point point1 = new Point();
point1.x = 50;
point1.y = 20;
Point point2 = new Point();
point2.x = 100;
point2.y = 20;
Point point3 = new Point();
point3.x = 150;
point3.y = 20;
// declare each ball with the ColorBall class
colorballs[0] = new ColorBall(context,R.drawable.bol_groen, point1);
colorballs[1] = new ColorBall(context,R.drawable.bol_rood, point2);
colorballs[2] = new ColorBall(context,R.drawable.bol_blauw, point3);
}
}
And my current class is:
public class Quiz1 extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.e);
AbsoluteLayout l= (AbsoluteLayout)findViewById(R.id.ll);
DrawView d=new DrawView(this);
l.addView(d);
}
}
I am trying to add that DrawView class but its not getting added as a child view of Absolutelayout of my current class view.its executing without any error but i am not able to see Drawview class objects.
And when i am doing this:
public class Quiz1 extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.e);
AbsoluteLayout l= (AbsoluteLayout)findViewById(R.id.ll);
DrawView d=new DrawView(this);
l.addView(d);
}
}
I am getting NullPointerException it means its not renderring the Drawview View.So bottom line is how to add a class extending a View to current view.
Please help me..thanx
The view probably is getting added, but from the code that you’ve posted it wouldn’t lay out in a way where anything would be visible. By default, when you add a view to a layout in Java code like you have done, without explicitly setting any
LayoutParams, it will set your view to be laid out usingwrap_contentfor both height and width. Since (as far as we can see) you are not overriding any of View’s measurement methods to tell the layout system how big the “content” inside your custom view is, the view will be added to the hierarchy with a height and width of zero.Before adding your custom view to the layout, you should add a line to set the layout parameters to fill it’s container (the parent layout), like so:
Another option is to add your custom view directly to the XML layout
R.layout.e, where you can set all these parameters directly in the XML and not worry about doing it in Java code.Final side note:
AbsoluteLayouthas been deprecated for a long time now, and should not be used in new applications. You should use aFrameLayoutorRelativeLayoutfor your application, which provide just as much flexibility.HTH