繁体   English   中英

将视图添加到自定义视图组

[英]Adding View to a Custom ViewGroup

我试图将视图添加到自定义ViewGroup。 将绘制ViewGroup,但是看不到添加到其中的View。 LineView的(扩展了View的)onDraw()方法不会被调用。 我究竟做错了什么?

 public class TestActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         ShapeView shapeView = new ShapeView(this);
         shapeView.setBackgroundColor(Color.RED);
         drawContainer = (RelativeLayout)findViewById(R.id.draw_container);
         drawContainer.addView(shapeView);   
    }
 }


 public class ShapeView extends ViewGroup {

     private LineView mLineView;

     public ShapeView (Context context) {
         super(context);
         RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(200, 200);
         this.setLayoutParams(p); 
         mLineView = new LineView(context);
         this.addView(mLineView);   
     }     
 }

我可能错了,但您不应该在shape“ main”中添加shapeView吗? 什么是drawContainer? 我看不到它被实例化,而不是在文档中。 我假设main包含相对/线性布局。

通过以下方式访问它:

RelativeLayout rel = (RelativeLayout) findViewById(R.id.container);

(更改ID以匹配您的ID)

然后:

rel.addView(shapeView);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM