How to make AppBarLayout background transparent
The same problem happened to me and at this point it has nothing to do with the transparency of the AppBarLayout
. But the AppBarLayout
pushes the content of your NestedScrollView
below itself when fading in.
You can solve this by
- moving your
NestedScrollView
up and behind theAppBarLayout
and - adding a space element to your
NestedScrollView
with the size of the AppBar
Step 1 can be easily achieved by adding this to your onCreate()
mNestedScroll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mNestedScroll.getViewTreeObserver().removeOnGlobalLayoutListener(this);
final int appBarHeight = mAppBar.getHeight();
mNestedScroll.setTranslationY(-appBarHeight);
mNestedScroll.getLayoutParams().height = mNestedScroll.getHeight() + appBarHeight;
}
});
For Step 2 you need to add an empty view with the height of the appBar as a spacer to your NestedScrollView
. Note: I used a RecyclerView
instead of a NestedScrollView
in my approach, so I had to add an empty ViewHolder with the appBarHeight to my RecyclerView. So this snippet is not tested, but it should do the trick for you:
<View
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"/>
Another option is to add negative top margin to NestedScrollView
(or whatever view is using appbar_scrolling_view_behavior
) and the same positive top margin (or padding) to its direct child:
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_marginTop="-100dp" >
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="100dp" >
...
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null" >
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|exitUntilCollapsed" >
...
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
Note that in order for this approach to work the AppBarLayout
should be placed below NestedScrollView
in the layout-file. In case fading edges of NestedScrollView
produce visual artifacts, add android:overScrollMode="never"
to its parameters. Also take care when using elevation
since it, when used in wrong place (say, when applied to whole AppBarLayout
), may also produce visual artifacts.