Android CollapsingToolbarLayout Java

With the new Design support library for Android, it has become easier for us to create some great animations with minimal effort , CollapsingToolbarLayout is the newly introduced in Lollipop , using which you can create awesome scrolling effects . With the new Design support library for Android, it has become easier for us to create some great animations with minimal effort ,



Build Gradle


Add the following lines to the dependencies section in your project's build.grade file and sync .
It include design support library , cardview library and palette library .

file : build.gradle

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.1'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation "androidx.palette:palette:1.0.0"

}

XML Layout


Create  XML layout file in res/layout and name it activity_main.xml

file : activity_main.xml
<androidx.coordinatorlayout.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <androidx.appcompat.widget.AppCompatImageView
                android:id="@+id/profile_id"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/pic1"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin" />

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffe5e5e5"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <!-- Scrollable content -->
        <include layout="@layout/content" />

    </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Lets Understand the XML Tags in the above xml layout

1. CoordinatorLayout
A powerful FrameLayout that specifies behavior for child views for various interactions. Allows floating views to be anchored in layout.

2. AppBarLayout 
Is essentially a LinearLayout (vertical). It helps respond to its children’s scroll events (scroll gestures). Responsible for implementing many features of material design’s app bar. Depends heavily on being used as a direct child within CoordinatorLayout.

3. CollapsingToolbarLayout 
Wrapper for Toolbar that makes the header image collapse into the Toolbar adjusting its title size.
What’s left is the ImageView which holds our actual header’s image and Toolbar which we’re familiar with.

4. NestedScrollView
It’s an special scroll view for the smooth scrolling effect, inside this place the desired content . Here in this example will add several Cards as its children.

Straight from the developer’s blog:

Flags include :
  1. scroll: this flag should be set for all views that want to scroll off the screen - for views that do not use this flag, they’ll remain pinned to the top of the screen.
  2. enterAlways: this flag ensures that any downward scroll will cause this view to become visible, enabling the ‘quick return’ pattern .
  3. enterAlwaysCollapsed: When your view has declared a minHeight and you use this flag, your View will only enter at its minimum height (i.e., ‘collapsed’), only re-expanding to its full height when the scrolling view has reached it’s top.
  4. exitUntilCollapsed: this flag causes the view to scroll off until it is ‘collapsed’ (its minHeight) before exiting .
Note : all views using the scroll flag must be declared before views that do not use the flag.This ensures that all views exit from the top, leaving the fixed elements behind.

For CollapsingToolbarLayout XML Tag set the layout_scrollFlags property with
 scroll|exitUntilCollapsed 

Collapse Mode
  • Parallax scrolling with the ImageView is achieved by simply setting its layout_collapseMode to parallax.
  • The Toolbar must use pin as its collapseMode because we want the Toolbar to persist and remain on top as the user scrolls down.
The XML Layout Inflate the view as below.



    MainActivity


    Now Inside the Activity we will see how to change the TextAppearance and Coloring of Toolbar Dynamically when Collapsing Toolbar  expands and collapse .

    1. Dynamic TextAppearance :

    A title which is larger when the layout is fully visible but collapses and becomes smaller as the layout is scrolled off screen. The title appearance can be tweaked via the collapsedTextAppearance and expandedTextAppearance attributes .

    Add the following style code inside the style.xml .


    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/primary</item>
            <item name="colorPrimaryDark">@color/primary_dark</item>
            <item name="colorAccent">@color/accent</item>
        </style>
    
        <style name="expandedappbar" parent="@android:style/TextAppearance.Medium">
            <item name="android:textSize">48sp</item>
            <item name="android:textColor">@color/white</item>
            <item name="android:textStyle">bold</item>
        </style>
    
        <style name="collapsedappbar" parent="@android:style/TextAppearance.Medium">
            <item name="android:textSize">18sp</item>
            <item name="android:textColor">@color/white</item>
        </style>
    
    </resources>
    


     collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
     collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);

    2. Dynamic Toolbar Coloring :  

    We’ll pass our image view’s bitmap to the Palette API, which will generate colors based on the image in an PaletteAsyncListener. Upon completion, we can fetch the color we want and set it to our CollapsingToolbarLayout,  which in turn will color our Toolbar when we scroll up.

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.profile_pic);
    
            Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(Palette palette) {
                    collapsingToolbarLayout.setContentScrimColor(palette.getMutedColor(R.attr.colorPrimary));
                    collapsingToolbarLayout.setStatusBarScrimColor(palette.getMutedColor(R.attr.colorPrimaryDark));
                }
            });
    The Complete MainActivity Source code

    file : MainActivity.java
    package com.tutorialsbuzz.collapsingtoolbardemo;
    
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    
    import androidx.appcompat.app.ActionBar;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    import androidx.palette.graphics.Palette;
    
    import com.google.android.material.appbar.CollapsingToolbarLayout;
    
    public class MainActivity extends AppCompatActivity {
    
        private CollapsingToolbarLayout collapsingToolbarLayout = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
    
            collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
            collapsingToolbarLayout.setTitle(getResources().getString(R.string.user_name));
    
            dynamicToolbarColor();
    
            toolbarTextAppernce();
        }
    
        private void dynamicToolbarColor() {
    
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.profile_pic);
    
            Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(Palette palette) {
                    collapsingToolbarLayout.setContentScrimColor(palette.getMutedColor(R.attr.colorPrimary));
                    collapsingToolbarLayout.setStatusBarScrimColor(palette.getMutedColor(R.attr.colorPrimaryDark));
                }
            });
        }
    
        private void toolbarTextAppernce() {
            collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
            collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);
        }
    
    }
    


    Scrolling Effect with Dynamic TextAppearance and Toolbar Coloring According to Image


    No comments:

    Post a Comment