Reputation: 1845
I have a custom component where I know the width and height is always as follows:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
I would like to avoid having to specify the width and height in XML since any other settings are wrong.
I've tried a lot of things, but nothing works. For example, this code doesn't work:
public class MyLayout extends ViewGroup {...
LayoutParams layoutParams =
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
setLayoutParams(layoutParams);
but no matter what I do, I get the exception message "You must supply a layout_width attribute." which goes away if I put back the XML layout_width
, layout_height
.
I've also tried to Override onFinishInflate()
, but that never gets called. I tried inheriting from View
, ViewGroup
and TableLayout
. I've tried calling getLayoutParams()
, but it returns null.
How do I get my custom component to not need these specified in XML?
Please no snark.
Thanks.
Upvotes: 1
Views: 3789
Reputation: 2415
You have the answer,
LayoutParams layoutParams = new LayoutParams(width, height); setLayoutParams(layoutParams);
height and width are specified in px, dip, sp
Alternatively, some of them provide with setHeight and setWidth methods, you can use them.
Upvotes: 1