Nicholas Roge
Nicholas Roge

Reputation: 160

layout_width and layout_height

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.

Upvotes: 2

Views: 843

Answers (5)

Renate
Renate

Reputation: 811

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

Upvotes: 0

Anand Sainath
Anand Sainath

Reputation: 1807

If reducing common and redundant attributes is what you want, then you should try styling.

Developer guide here.

Upvotes: 0

Romain Guy
Romain Guy

Reputation: 98541

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.

Upvotes: 2

Orkun
Orkun

Reputation: 7268

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.

Upvotes: 0

Dave
Dave

Reputation: 121

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

Upvotes: 0

Related Questions