Skip to content
Related Articles

Related Articles

Improve Article

How to Use Morphy Toolbar Library in Android App?

  • Last Updated : 11 Jul, 2021
Geek Week

MorphyToolbar is a library that allows us to have a custom toolbar with a title, subtitle, and a picture that further offers the possibility to animate the view between transitions. This library is extremely easy to integrate and offers several customizations. In this article, we will be implementing this library in an Android App using Java language. A sample GIF is given below to get an idea about what we are going to do in this article. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add JitPack 



Navigate to the Gradle Scripts > build.gradle(Project: Project Name), add jitpack at the end of repositories, and sync the project.

maven { url "https://jitpack.io" }

Step 3: Add the library dependency 

Navigate to the Gradle Scripts > build.gradle(Module:app), add the library in the dependencies section, and sync the project.

dependencies {
    implementation 'com.github.badoualy:morphy-toolbar:1.0.4'  
}

Step 4: Working with the styles.xml file

Navigate to the app > res > values> styles.xml and add the below code to that file. Below is the code for the styles.xml file. 

XML






<resources>
    <!-- Base application theme. -->
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionModeOverlay">true</item>
        <item name="windowActionBarOverlay">true</item>
  
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>>
    </style>
  
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
  
    <style name="ToolbarStyle" parent="Widget.AppCompat.Toolbar">
        <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
    </style>
  
</resources>

Step 5: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<!--Use Coordinator Layout -->
<android.support.design.widget.CoordinatorLayout 
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <android.support.design.widget.AppBarLayout
        android:id="@+id/layout_app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">
  
        <!--Toolbar-->
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            style="@style/ToolbarStyle"
            android:layout_width="match_parent"
            android:layout_height="@dimen/mt_toolbar_height"
            android:background="#0F9D58"
            android:minHeight="@dimen/mt_toolbar_height"
            app:title=""
            app:titleTextColor="#FFFFFF" />
  
    </android.support.design.widget.AppBarLayout>
  
    <!--Floating Action Button is attached to 
        the AppBarLayout using app:layout_anchor.-->
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:src="@drawable/ic_photo_camera_white_24dp"
        android:tint="#797979"
        app:backgroundTint="#FFFFFF"
        app:layout_anchor="@id/layout_app_bar"
        app:layout_anchorGravity="center_vertical|end|right" />
  
</android.support.design.widget.CoordinatorLayout>

Step 6: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
  
import com.github.badoualy.morphytoolbar.MorphyToolbar;
  
public class MainActivity extends AppCompatActivity {
  
    MorphyToolbar morphyToolbar;
      
    // primary2 determines the color 
    // of morphyToolbar when expanded
    int primary2 = Color.parseColor("#fbc757");
      
    // primaryDark2 determines the color
    // of status bar when expanded
    int primaryDark2 = Color.parseColor("#e6b449");
  
    AppBarLayout appBarLayout;
    Toolbar toolbar;
    FloatingActionButton fabPhoto;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        appBarLayout = findViewById(R.id.layout_app_bar);
        toolbar = findViewById(R.id.toolbar);
        fabPhoto = findViewById(R.id.fab_photo);
  
        disableAppBarDrag();
          
        // disableAppBarDrag() disables the scrolling-of
        // AppBarLayout in CoordinatorLayout
        // i.e prevents the user from hiding
        // the ToolBar when swiped above
        hideFab();
          
        // hideFab() hides the floating action button
        // Attaching MorphyToolbar to the given activity/toolbar
        morphyToolbar = MorphyToolbar.builder(this, toolbar)
                .withToolbarAsSupportActionBar()
                // Title of Toolbar
                .withTitle("GeeksForGeeks DS and Algorithms Course")
                // Subtitle of Toolbar
                .withSubtitle("16,000 Participants")
                // Adding image to the toolbar
                .withPicture(R.drawable.gfgicon)
                // if you want to hide the img when 
                // AppBarLayout collapses, set it to true
                .withHidePictureWhenCollapsed(false)
                .build();
  
        morphyToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // if morphyToolbar is collapsed, expand it
                // and if expanded, collapse it.
                if (morphyToolbar.isCollapsed()) {
                    morphyToolbar.expand(primary2, primaryDark2,
                            new MorphyToolbar.OnMorphyToolbarExpandedListener() {
                                @Override
                                public void onMorphyToolbarExpanded() {
                                    // shows the floating action button
                                    // when morphyToolbar expands
                                    showFab();
                                }
                            });
                } else {
                    // hides the floating action 
                    // button when morphyToolbar collapses
                    hideFab();
                    morphyToolbar.collapse();
                }
            }
        });
  
        // adding a back button
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP
                    | ActionBar.DISPLAY_SHOW_TITLE
                    | ActionBar.DISPLAY_SHOW_CUSTOM);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }
  
    private void disableAppBarDrag() {
        // disables the scrolling-of AppBarLayout in CoordinatorLayout
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = new AppBarLayout.Behavior();
        params.setBehavior(behavior);
        behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
            @Override
            public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                return false;
            }
        });
    }
  
    // These two methods hideFab() & showFab() are 
    // for hiding and showing the floating
    // action button, which is to be used only 
    // if you are adding a floating action button.
    private void hideFab() {
        fabPhoto.show();
        fabPhoto.hide();
        final CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) fabPhoto.getLayoutParams();
        layoutParams.setAnchorId(View.NO_ID);
        fabPhoto.requestLayout();
        fabPhoto.hide();
    }
  
    private void showFab() {
        final CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) fabPhoto.getLayoutParams();
        layoutParams.setAnchorId(R.id.layout_app_bar);
        layoutParams.anchorGravity = Gravity.RIGHT | Gravity.END | Gravity.BOTTOM;
        fabPhoto.requestLayout();
        fabPhoto.show();
    }
  
    @Override
    public void onBackPressed() {
        // if morphyToolbar is already
        // collapsed finish the activity
        // else collapse the toolbar
        if (!morphyToolbar.isCollapsed()) {
            hideFab();
            morphyToolbar.collapse();
        } else
            super.onBackPressed();
    }
  
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // It is called, when a user
                // presses back button
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Output: 

GitHub Repository: MorphyToolbarLibrary

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :