简体   繁体   中英

How to know if widgets width is set to wrap_content

I am creating a custom view which extends LinearLayout . I'm adding some shapes to the linear layout, currently with a fixed value of space between them. I'm doing so by defining a LayoutParams and setting the margins to create the space between the shapes.

What I want to do is span them at an equal space across the entire screen so they would fill it, but only if the width of the view is set to either match_parent or fill_parent . If it's set to wrap_content then the original fixed value of space should be set.

I've tried doing:

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
   super.onMeasure(widthMeasureSpec, heightMeasureSpec);
   int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
   spaceBetweenShapesPixels = (parentWidth - shapeWidth * numberOfShapes) / numberOfShapess;
}

However, the method seems to be called twice - Once for the width and height of the parent and after that for the View's itself and when it's for the view itself, the space gets a 0 value.

So how can I just make this logic:

if(width is wrap_content)
{
   space = 10;
}
else
{
   space = (parentWidth - shapeWidth * numberOfShapes) / numberOfShapess;
}

You should use WidthMode and HeightMode In the onMeasure() method. Below is sample a from one of my projects

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int measuredWidth = 0, measuredHeight = 0;

if (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST) {
  measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
}

if (heightMode == MeasureSpec.EXACTLY) {
  measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
} else if (heightMode == MeasureSpec.AT_MOST) {
  double height = MeasureSpec.getSize(heightMeasureSpec) * 0.8;
  measuredHeight = (int) height;// + paddingTop + paddingBottom;
}
}

MeasureSpec.EXACTLY - A view should be exactly this many pixels regardless of how big it actually wants to be.

MeasureSpec.AT_MOST - A view can be this size or smaller if it measures out to be smaller.

MeasureSpec.UNSPECIFIED - A view can be whatever size it needs to be in order to show the content it needs to show.

Refer this for more details https://stackoverflow.com/a/16022982/2809326

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM