Android(MeasureSpec): When Is it possible to get both height and width as "MeasureSpec.UNSPECIFIED"

967 views Asked by At

I am programming my own layout, extending the ViewGroup class. One of the meethod you need to override is the onMeasure() method. In this method, the parent View (the view that will contain my layout) will pass the posible width and height my layout can have.

@Override
public class MyOwnLayout extends ViewGroup {

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        // Argumens passed by the parent View.
        // Can be both arguments be as MeasureSpec.UNSPECIFIED simultaneously ??
    }

}

This MeasureSpec arguments can have three possible modes: "EXACLY", "AT_MOST" and "UNSPECIFIED" (The meaning of them are here. Specifically, "UNSPECIFIED" value is passed by the parent when my layout can be of any size it wants in that specific dimension. This is given, for example, when the parent is a ScrollView.

So my only doubt is: It is possible for the parent to pass to my layout both of them as UNSPECIFIED simultaneously. If possible, in which cases?

1

There are 1 answers

1
William On BEST ANSWER

You could make a custom view which scrolls in both directions. This would (or could) measure its children with UNSPECIFIED in both height and width. It's possible that a HorizontalScrollView nested in a ScrollView will cause this behaviour as well, but that isn't recommended.

Typically, this case (both UNSPECIFIED) will not come up. It's probably okay to not ignore it. However, I've found that ignoring technically legal configurations to be a good way to introduce weird bugs in the future. You should handle this case in your onMeasure if you can.