Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 534
Blair Jones Avatar asked Aug 18 '10 19:08

Blair Jones


1 Answers

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.

like image 127
Mathias Conradt Avatar answered Sep 23 '22 20:09

Mathias Conradt