7

我有一个自定义视图(TextView 的扩展),我想动态添加到我的布局中(不想将它包含在 main.xml 文件中)。

这本书说要在我的 java 代码中使用 findViewById() 获取 RelativeLayout,然后创建我的自定义视图的新实例,然后在 RelativeLayout 上使用 addView 来添加新视图。

我没有收到任何错误,但是当我单击按钮添加新视图时,什么都没有发生(未添加视图)。我是否需要在我的自定义视图(例如布局宽度、布局高度)上设置其他属性才能显示它?

编辑:添加代码

// changed to an imageview as I thought it might be easier to see an image
RelativeLayout rel = (RelativeLayout) findViewById(R.id.rellay);
MyCustomImageView mciv = new MyCustomImageView(null);
mciv.setId(5);
LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mciv.setLayoutParams(p);
mciv.setImageResource(R.drawable.someImage);
rel.Addview(mciv);
4

1 回答 1

3

请在添加视图的位置发布您的代码。但是,是的,您可能缺少宽度和高度的参数。尝试类似的东西

LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT);    
txtView.setLayoutParams(p);

或者你想要的宽度和高度。同样在 xml 布局中,layout_width 和 layout_height 是必需的属性。

于 2010-08-18T19:26:08.860 回答