2011-12-05 57 views
0

我有一个类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); 


    } 
    } 

而且我现在的类是:

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函数类,但其没有得到作为我的当前类视图的绝对布局的子视图添加没有任何错误执行,但我无法看到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这意味着它不是renderring的drawView函数View.So底线是如何添加一个扩展来查看当前视图的类。 请帮助me..thanx

回答

0

的观点可能获取添加,但你已经张贴不会在某种程度上什么地方会是可见的铺陈代码。默认情况下,当您像使用Java代码一样在Java代码中添加视图时,如果未明确设置任何LayoutParams,则会将视图设置为使用wrap_content表示高度和宽度。因为(就我们所能看到的)而言,您不覆盖View的任何测量方法来告诉布局系统自定义视图内的“内容”有多大,视图将被添加到高度和宽度为零的层次结构中。

之前添加自定义视图的布局,你应该添加一行来设置布局参数,以填补它的容器(父布局),像这样:

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); 

另一种方法是添加自定义的直接查看XML布局R.layout.e,您可以直接在XML中设置所有这些参数,而不用担心在Java代码中执行这些参数。

最终方面备注:AbsoluteLayout现在已经被弃用了很长一段时间,不应该在新的应用中使用。您应该为您的应用程序使用FrameLayoutRelativeLayout,它们提供了同样的灵活性。

HTH

+0

感谢名单Devunwired我想谈一下我的问题跟你说,如果我会做只的setContentView(新drawView函数(本)),那么我能够看到这种观点,我不能这样做在XML bcoz我drawView函数类正在处理复杂的图像拖放工作等。请帮助我。 –

相关问题