Is there any way I can get around having to add the layout_width and layout_height parameters to my custom views? I know there are a few built in android views that you don't have to supply those attributes for.
5 Answers
It's not a View's responsibility to decide whether or not it can/should provide these attributes. The parent ViewGroup dictates whether these attributes are mandatory or not. TableRow for instance makes them optional. Other layouts (LinearLayout, FrameLayout, etc.) require these params.
1 Comment
When would you want to not use the height and width parameters? I'm not sure but I think that would cause them to not even show up on the layout?
Look here for reference http://developer.android.com/guide/topics/ui/declaring-layout.html#layout-params
1 Comment
From the same Reference Dave has suggested.
All view groups include a width and height (layout_width and layout_height), and each view is required to define them. Many LayoutParams also include optional margins and borders.
So it looks like, you have to.
4 Comments
ViewGroup but it says it s an abstract class (developer.android.com/reference/android/view/ViewGroup.html) The classes that extend it, however, they implement layout_height and layout_widthIf reducing common and redundant attributes is what you want, then you should try styling.
Developer guide here.
1 Comment
The problem is that ViewGroup.LayoutParams.setBaseAttributes() uses the strict getLayoutDimension(int, String). You need to extend whichever LayoutParams you need and override setBaseAttributes. Inside you can either manually set width and height or use the more lenient getLayoutDimension(int, int). Finally, you'll have to override in your layout class that you are using your own LayoutParams.
@Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } public static class LayoutParams extends FrameLayout.LayoutParams { public LayoutParams(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { width = a.getLayoutDimension(widthAttr, WRAP_CONTENT); height = a.getLayoutDimension(heightAttr, WRAP_CONTENT); } }