要解决这个问题,您可以使用一个自定义的AppBarLayout,其中包含一个MotionLayout,并在布局文件中使用自定义的AppBarLayout代替默认的AppBarLayout。以下是一个示例代码:
首先,创建一个名为CustomAppBarLayout的自定义AppBarLayout类:
public class CustomAppBarLayout extends AppBarLayout {
private MotionLayout mMotionLayout;
public CustomAppBarLayout(Context context) {
super(context);
}
public CustomAppBarLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomAppBarLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// 查找布局文件中的MotionLayout
mMotionLayout = findViewById(R.id.motionLayout);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 测量MotionLayout的高度
int motionLayoutHeight = mMotionLayout.getMeasuredHeight();
// 设置AppBarLayout的高度为MotionLayout的高度
setMeasuredDimension(getMeasuredWidth(), motionLayoutHeight);
}
}
在布局文件中使用CustomAppBarLayout代替默认的AppBarLayout,并将MotionLayout添加到CustomAppBarLayout中,如下所示:
这样,当你使用android:layout_height="wrap_content"时,CustomAppBarLayout将会测量MotionLayout的高度,并将自身的高度设置为MotionLayout的高度,从而实现了android:layout_height="wrap_content"的效果。