dynamically adding a view to activity layout

I have a custom view (an extension of a TextView) that I want to dynamically add to my Layout (don't want to include it in the main.xml file).

The book says to fetch the RelativeLayout using findViewById() in my java code then create a new instance of my custom view, then use addView on the RelativeLayout to add the new view.

I'm not getting any errors, but when I click my button to add the new view, nothing is happening (view isn't being added). Do I need to set additional properties on my custom view (layout width, layout height for example) in order for it to be shown?

EDIT: adding code

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

Please post your code where you add the view. But yes, you might be missing the params for width and height. Try something like

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

or what you would like the width and height to be. Also in xml layout, layout_width and layout_height are required attributes.

链接地址: http://www.djcxy.com/p/2434.html

上一篇: 我如何处理一个包含数百个HTML项目的列表? (使用Javascript)

下一篇: 动态地将视图添加到活动布局