Android 如何将类扩展视图添加到当前类视图
我有一个类Drawview:Android 如何将类扩展视图添加到当前类视图,android,Android,我有一个类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) {
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);
}
}
我现在的课程是:
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);
}
}
我正在尝试添加该DrawView类,但它没有被添加为当前类视图的Absolutelayout的子视图。它执行时没有任何错误,但我无法看到DrawView类对象。
当我这样做的时候:
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);
}
}
我得到了NullPointerException,这意味着它不会呈现Drawview视图。所以底线是如何添加一个将视图扩展到当前视图的类。
请帮帮我..thanx视图可能正在添加,但从您发布的代码来看,它不会以任何可见的方式显示出来。默认情况下,在Java代码中将视图添加到布局时,如您所做的那样,没有显式设置任何LayoutParams,它会将视图设置为使用高度和宽度的wrap_内容进行布局。因为就我们所见,您没有覆盖视图的任何测量方法来告诉布局系统自定义视图中的内容有多大,因此视图将以零的高度和宽度添加到层次中
在将自定义视图添加到布局之前,应添加一行以设置布局参数,以填充其父布局的容器,如下所示:
AbsoluteLayout l= (AbsoluteLayout)findViewById(R.id.ll);
DrawView d = new DrawView(this);
LayoutParams lp = new AbsoluteLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0, 0);
d.setLayoutParams(lp);
l.addView(d);
另一种选择是将自定义视图直接添加到XMLLayout R.layout.e中,在这里您可以直接在XML中设置所有这些参数,而不用担心在Java代码中进行设置
最后一个旁注:AbsoluteLayout已经被弃用很长时间了,不应该在新的应用程序中使用。您应该为您的应用程序使用FrameLayout或RelativeLayout,它们提供了同样多的灵活性
HTHthanx Devunwired我想与您讨论我的问题,如果我只做setContentViewnew Drawview,那么我可以看到该视图,我不能在xml中看到它。因为我的Drawview类正在处理图像拖放等复杂工作。请帮助我。。