【问题标题】:Adding View to a Custom ViewGroup将视图添加到自定义视图组
【发布时间】:2012-01-09 01:17:31
【问题描述】:

我正在尝试将视图添加到自定义视图组。 ViewGroup 被绘制,但添加到其中的视图不可见。 LineView(扩展视图)的 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);   
     }     
 }

【问题讨论】:

    标签: android


    【解决方案1】:

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

    通过以下方式访问它:

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

    (其中 id 更改为与您的 id 匹配)

    然后:

    rel.addView(shapeView);
    

    【讨论】:

    • 抱歉,忘记将那行代码粘贴到问题中。已更新。
    • 不,没关系,我以为是 50/50。好的,那么您实际上看到了什么?你有红色方块吗?还是什么也没看到?
    • 我只看到红色方块,没有别的。我觉得我应该在我的 onLayout() 方法中添加一些东西,但我不确定它的用途以及如何正确编码。
    • 我在文档中也看不到 LineView。这是你的另一门课吗?如果是这样,可能值得添加它。
    • 一旦我实现了 ViewGroup 的 onLayout() 方法,它就起作用了 :)
    猜你喜欢
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多