ExpansionPanel
ExpansionPanel copied to clipboard
Expansion after init does not work
Hello, thank you for the library.
I stumbled on a bug while using the expansion panel in a recycler view.
I need to handle the expansion manually, so I'm using collapse(boolean animated)
and expand(boolean animated)
to update the expansion layout accordingly.
It works fine, except when initializing the layout state to expanded. The layout is not expanded by default (in the XML) but set to expanded (expand(false)
) by the adapter when the activity starts.
I think the cause is:
-
expand(false)
is called by the adapter.expanded
is set to true, but we don't have a height yet - the
ViewTreeObserver
for preDraw is called - the
preDraw
callback tries to update the height of the layout since it'sexpanded
https://github.com/florent37/ExpansionPanel/blob/ffd431de78a51c594d1d78f4c46697708105a878/expansionpanel/src/main/java/com/github/florent37/expansionpanel/ExpansionLayout.java#L133-L136 -
expand(false)
is called but returns early sinceexpanded
is true https://github.com/florent37/ExpansionPanel/blob/ffd431de78a51c594d1d78f4c46697708105a878/expansionpanel/src/main/java/com/github/florent37/expansionpanel/ExpansionLayout.java#L207-L210 - and so,
setHeight
is never called with the expanded height
If that's the case, I think updating the preDraw callback to
//now we have a size
if (expanded) {
setHeight(getChildAt(0).getHeight());
}
might be the fix. I can do a PR for this if you want.
The same problem seem to be present in the horizontal version, though I haven't tested it.
@AoDevBlue You can use separate thread to handle such case. It may help
+1 on this issue Thanks for the lib and thanks @esnaultdev for the fix idea, it should be PR'd :)
In the meanwhile I made myself a workaround with a subclass of expansion layout
class ExpansionLayout2(context: Context, attrs: AttributeSet?) : ExpansionLayout(context, attrs) {
override fun expand(animated: Boolean) {
if (isExpanded() && isEnabled()) {
val height = getChildAt(0).getHeight();
// setHeight(height)
// setHeight is private, so let's copy its contents instead of calling it :
val layoutParams = layoutParams
if (layoutParams != null) {
layoutParams.height = height
setLayoutParams(layoutParams)
}
}
else
expand(animated, true)
}
}
and for sure replacing in the layout file
<com.github.florent37.expansionpanel.ExpansionLayout
android:id="@+id/myExpansionLayoutId2"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<!-- CONTENT -->
</com.github.florent37.expansionpanel.ExpansionLayout>
with
<mypackage.path.ExpansionLayout2
android:id="@+id/myExpansionLayoutId2"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<!-- CONTENT -->
</mypackage.path.ExpansionLayout2>