Search code examples
androidandroid-appbarlayout

How to make AppBarLayout background transparent


I'm trying to make a search fragment similar to the one in the Play Store:

Google Play Store

My AppBarLayout has a CardView in it, and the background is set to transparent:

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:elevation="0dp">

        <!-- CardView -->

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <!-- Main content -->

    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

But as you can see, there is a solid background behind the CardView so that the content behind it is hidden:

Hidden content

How can I make the AppBarLayout's background transparent so that the content behind is visible?


Solution

  • 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

    1. moving your NestedScrollView up and behind the AppBarLayout and
    2. 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"/>