views:

173

answers:

1

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);
A: 

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.

Mathias Lin
ok I changed the custom view to be an imageview because I thought that would be easier to see on the Activity. I edited my OP to include some code...still not seeing anything. Since it's a relative view, do I need to include something to tell it where to put it in the AddView() method?
Blair Jones
in xml it would be like android:layout_below or android:layout_toRightOf, but not sure if it's required or how to put it in java code adhoc.
Mathias Lin
hmm...ya I knew the xml bit, but I want this to happen programatically. I just tried putting it on a different thread thinking that could be the problem (can't update the UI on the same thread, and that didn't fix it). I'm at a loss.
Blair Jones
aha! I needed to pass "this" instead of a null to the customview declaration. I'll mark your response as the answer as I'm sure I needed the params anyway :P thanks much.
Blair Jones