google / flexbox-layout

Flexbox for Android
Apache License 2.0
18.25k stars 1.79k forks source link

FlexboxLayout children not visible when width is unconstrained (such as within a horizontal recycler view) #589

Open OlivierGenez opened 3 years ago

OlivierGenez commented 3 years ago

Issues and steps to reproduce

When FlexboxLayout's' width is unconstrained (i.e. the width MeasureSpec mode is UNSPECIFIED), its children views are not measured/laid out correctly, resulting in them being not visible.

This is relatively easy to replicate:

Expected behavior

The FlexboxLayout child TextView should be visible (i.e. allowed to be the width it wants).

Version of the flexbox library

Notes

It seems the issue was introduced by this change: https://github.com/google/flexbox-layout/pull/521/files.

Looking at the current version of the corresponding code:

if (widthMode == View.MeasureSpec.EXACTLY) {
    mainSize = widthSize;
} else {
    mainSize = Math.min(largestMainSize, widthSize);
}

it seems to me that mainSize = Math.min(largestMainSize, widthSize); should only apply when widthMode == View.MeasureSpec.AT_MOST, but I might be missing something. I believe the logic should be instead:

if (widthMode == View.MeasureSpec.EXACTLY) {
    mainSize = widthSize;
} else if (widthMode == View.MeasureSpec.AT_MOST) {
    mainSize = Math.min(largestMainSize, widthSize);
} else {
    mainSize = largestMainSize;
}

I've tested this change on a local branch and it behaves as expected. If that seems right to you I'm happy to open a PR with this change + tests.

In the current state, having mainSize set to widthSize will cause the flex shrink logic to be applied, which will force the children sizes to be something else than the width they want to/should be. Note that disabling flex shrink result in the expected behaviour and is a temporary workaround.

Link to code

Here is a link to as simple project which demonstrates the issue: https://github.com/OlivierGenez/flexbox-layout-unconstrained-width-bug.