Welcome to Android CollapsingToolbarLayout Example. In this tutorial, we’ll discuss and implement CollapsingToolBarLayout in our application.
Android CollapsingToolbarLayout is a wrapper for Toolbar which implements a collapsing app bar. It is designed to be used as a direct child of a AppBarLayout. This type of layout is commonly seen in the Profile Screen of the Whatsapp Application. This layout consists of:
If you’ve updated to the latest SDK recently choose the Scrolling Activity type (it contains a ready-made implementation of CollapsingToolbarLayout) while creating a new project. Running the default new project should show an output like this: In this tutorial, we’ll be doing changes in the default project such as showing an ImageView, showing the toolbar equivalent icon from the FAB button, when it’s collapsed.
The activity_scrolling.xml
is given below:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.journaldev.collapsingtoolbarlayout.ScrollingActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="@dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="@+id/expandedImage"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:src="@drawable/photo"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_scrolling" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/fab_margin"
app:layout_anchor="@id/app_bar"
app:layout_anchorGravity="bottom|end"
app:srcCompat="@android:drawable/ic_dialog_info" />
</android.support.design.widget.CoordinatorLayout>
app:layout_anchor
and app:layout_anchorGravity
anchors the FAB to the bottom right of the AppBarLayout Note: content_scrolling.xml
stays as the default for this tutorial. The menu_scrolling.xml
file is defined as given below
<menu xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
tools:context="com.journaldev.collapsingtoolbarlayout.ScrollingActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
<item
android:id="@+id/action_info"
android:orderInCategory="200"
android:title="info"
app:showAsAction="ifRoom"
android:icon="@android:drawable/ic_dialog_info"/>
</menu>
The code for ScrollingActivity.java
is defined below:
package com.journaldev.collapsingtoolbarlayout;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class ScrollingActivity extends AppCompatActivity {
private Menu menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
final Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
AppBarLayout mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
isShow = true;
showOption(R.id.action_info);
} else if (isShow) {
isShow = false;
hideOption(R.id.action_info);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_scrolling, menu);
hideOption(R.id.action_info);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_info) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void hideOption(int id) {
MenuItem item = menu.findItem(id);
item.setVisible(false);
}
private void showOption(int id) {
MenuItem item = menu.findItem(id);
item.setVisible(true);
}
}
In the above code, to know whether the CollapsingToolbarLayout
is collapsed or expanded, we add a listener addOnOffsetChangedListener on the AppBarLayout instance. Depending upon the if else conditions we show or hide the toolbar info option. The output of the application in action is given below This brings an end to this tutorial. You can download the Android CollapsingToolbarLayout Project from the link given below.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
At the moment when you call the last two methods, it gives an error saying that menu is a null object. And when I look back at your code I noticed that you are not initializing menu in onCreate method but in onCreateOptions method. I thought that onCreate will be called before onCreateOptions.
- emmanuel agyapong
Many thanks for this tutorial ! ? Thanks to @Bangonkali too for the fork
- Matdev
How to change the title manually using JAVA file ?
- Xaif
Sharing this fork of this project with AndroidX support. https://github.com/bangonkali/CollapsingToolbarLayout
- Bangonkali
Hello thank for all Please I want create book app , how can I do ?
- Guillaume Lewis
hi anupam, thanks for great tutorial. I appreciate your efforts to create this tutorial. I have a question. what if title of toolbar is long… is there any way we can wrap the text in this toolbar?
- Muddassir
Thank you. This helped me out !
- Elyes
Very nicely done. Thank you for spending the time and effort in sharing this :) Saved me hours of troubleshooting and learnt along the way.
- Julian Mummery
Thank you so much
- ASHUTOSH DUBEY
best post
- فروشگاه خرید اینترنتی