Android CollapsingToolbarLayout – Material Design Tutorial -2

Android CollapsingToolbarLayout:

In this tutorial, we will learn to create a collapsing toolbar layout that was introduced with Design Support library . 
Before starting anything, let’s check for the new layouts that were introduced with design library :

CoordinatorLayout :

This is a super powered FrameLayout. We can specify behaviours for child views of coordinatorlayout for various interections.

Appbar Layout: 
AppBarLayout should be used as a direct child of coordinatorLayout. Basically, it is a vertical Linear Layout , children of which can manage the behaviour when the content is scrolled. setScrollFlags(int) or app:layout_scrollFlags is used to provide their children their desired scrolling behavior.

CollapsingToolbarLayout :
This layout is a wrapper for toolbar which implements a collapsing app bar . It is used as a direct child of AppBarLayout.

 collapsingtoolbar

CollapsingToolbarLayout has the following features :

Collapsing title :

A Title that is larger when the layout is fully visible and becomes smaller when the layout is scrolled off the screen. setTitle(CharSequence)can be used to set the title .collapsedTextAppearance and expandedTextAppearance attributes are used to change the title appearance.

Content scrim :
A full-bleed scrim that will be shown or hidden when the scroll position has hit a certain threshold.We can change it using setContentScrim(Drawable).

Status bar scrim:
A scrim that will be shown or hidden behind the status bar when the scroll position hits a threshold value.
setStatusBarScrim(Drawable) can be used to change this. This will work only on lollipop devices.

Sample Application :

1. Create a project on Android Studio with an Activity “ScrollingActivity” and its corresponding layout “activity_scrolling.xml” .

public class ScrollingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.toolbar_layout);
        setSupportActionBar(toolbar);

        final 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();
            }
        });

        //get the bitmap of the drawable image we are using as background
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.amsterdam);


        //using palette, change the color of collapsing toolbar layout
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            public void onGenerated(Palette palette) {
                int mutedColor = palette.getMutedColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
                int mutedDarkColor = palette.getDarkMutedColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryDark));
                int vibrantColor = palette.getVibrantColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent));

                collapsingToolbarLayout.setContentScrimColor(mutedColor);
                collapsingToolbarLayout.setStatusBarScrimColor(mutedDarkColor);
                fab.setBackgroundTintList(ColorStateList.valueOf(vibrantColor));

            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        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;
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_scrolling.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.sampletest.democollapsingtoolbar.ScrollingActivity">
<!--image used is downloaded from : https://pixabay.com/en/amsterdam-night-canals-evening-1150319/-->
    <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:background="@drawable/amsterdam"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <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"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end" />

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

content_scrolling.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.sampletest.democollapsingtoolbar.ScrollingActivity"
    tools:showIn="@layout/activity_scrolling">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:text="@string/large_text" />

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

You can see in the activity_scrolling.xml file that CoordinatorLayout is the base layout and AppbarLayout is working as parent layout of CollapsingToolbarLayout.

Also we are using the palette library to change the Content Scrim and StatusBar Scrim color of the collapsing toolbar layout in the ScrollingActivity :

collapsingToolbarLayout.setContentScrimColor(mutedColor);           

collapsingToolbarLayout.setStatusBarScrimColor(mutedDarkColor);

That’s it. Cone this project from github here and try to run it . If you have any query or if you are having any problem running this project, please comment below.

Android Toolbar – Material Design Tutorial -1

Android Toolbar was introduced with Android Lollipop (API 21) .Toolbar can be used as a replacement for for android ActionBar. Toolbar was designed for Lollipop devices, but we can use it on Pre-Lollipop devices using google’s AppCompat library. android.support.v7.widget.Toolbar class is used to implement ToolBar in this library.

Why Should you use Toolbar ?
– Implemented following Material Design
– You can have multiple Toolbars ( We can say toolbar is an ActionBar with more control on it. We can use toolbar as like other “view” s. We can create one toolbar at bottom or one more as floating Toolbar ( like google maps). Also we can use two different menu on two different toolbars )

– You can add more custom views into your toolbar , Also since it is actually a “View”  object, we can do any other things that can be done to a normal “view” object. Like we can show/hide it anytime we want or we can change its color dynamically ( this is we are going to discuss in this example) etc.

toolbar

1) Create one application in Android Studio

2) Add appcompat as gradle dependency

dependencies {
compile 'com.android.support:appcompat-v7:23.1.1'
}

3) Create color.xml file inside ‘values’ folder

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#FF5722</color>
    <color name="colorPrimaryDark">#E64A19</color>
</resources>

4) Disable ActionBar in the Application Theme (inside values/styles.xml) :

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    </style>
</resources>

5) Create one file toolbar.xml inside “layout” folder

<?xml version="1.0" encoding="utf-8"?>    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"     
android:layout_width="match_parent"     
android:layout_height="wrap_content"     
android:background="@color/colorPrimary"     
android:elevation="4dp"     
/>

6) Change your activity_main.xml layout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        ></include>
</RelativeLayout>

7) Finally add this toolbar as actionbar in your MainActivity :

 private Toolbar toolbar;   
 toolbar = (Toolbar) findViewById(R.id.tool_bar);
 setSupportActionBar(toolbar);

8) Update your MainActivity.java file as below :

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Toolbar toolbar;
    private Button button;
    private Window window;
    private int i = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);

        button = (Button) findViewById(R.id.button);
        window = this.getWindow();

        if (android.os.Build.VERSION.SDK_INT > 18) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        if (android.os.Build.VERSION.SDK_INT > 20) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        }

        button.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (i) {
            case 0:
                toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                if (android.os.Build.VERSION.SDK_INT > 20) {
                    window.setStatusBarColor(getApplicationContext().getResources().getColor(R.color.colorPrimaryDark));
                }
                break;
            case 1:
                toolbar.setBackgroundColor(getResources().getColor(R.color.redNormal));
                if (android.os.Build.VERSION.SDK_INT > 20) {
                    window.setStatusBarColor(getApplicationContext().getResources().getColor(R.color.redDark));
                }
                break;
            case 2:
                toolbar.setBackgroundColor(getResources().getColor(R.color.tealNormal));
                if (android.os.Build.VERSION.SDK_INT > 20) {
                    window.setStatusBarColor(getApplicationContext().getResources().getColor(R.color.tealDark));
                }
                break;
        }
        i++;
        i = i % 3;
    }
}

it will change your toolbar color on each click.

Notes :
If you want to change toolbar text colors to light , use this theme inside toolbar layout :
android:theme="@style/ThemeOverlay.AppCompat.Dark"
-Similarly if you want your popup theme as light , use this :
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"

This Project is shared on github. You can clone it from here.

Git Tutorial 3 – Git with android studio

git
Git can be used easily with Android Studio. (We will not discuss in detail about the git commands in this tutorial. Please check Git Tutorial 1 and Git Tutorial 2 if you find any problem) . So,in this tutorial, we will learn how to create , commit and push a new project to github and pull an existing project from github using Android Studio.
 
1.Check git is installed or not on your System :
 
a) Open Android Studio and create a new Sample Project.
b) Click on File->Settings -> Versioin Control-> Git

c) Click on “Test” near “Path to Git Executable”

 

 git1
 
if “Git Executed successfully” message is displayed it means that git is already installed on your system.
 
Step 1 : “git init”
git2
 
VCS -> “Enable Version Control Integration” -> and select “Git” from the dropdown list as shown above
 
 
Step 2 : “Git remote add origin”
 
For this step , we should use “git bash” or if you have installed git integrating with command prompt , we can use it from  Android studio terminal.
 
 a) Using android studio terminal :
git3
 
Step 3 : “git add”
VCS -> git -> Add
(Note that you should select your project before clicking “Add”  like below )
 
git4
 
Everything added newly to git will be marked with green.
 
git5
Step 4 :
If you add any new files in future, Android studio will ask to add these files to git or not as :
 git6
 
Step 5 : “git commit”
Click on VCS-> “Commit Changes”
 
git7
 
 write one commit message and click on Commit . Now all files will be back to its normal color.
 
If you make any new changes to an already committed file, its color will be turned to blue.
 
git8
 
 
i.e. Red – File is not added to git
      Green – File is added but not committed yet
      Blue – New changes is added to a file that is committed to git already
 
 
Step 6: “git push”
 VCS -> Git -> push
 git9
 
this will push your changes to git server repository.
 
Step 7: To clone a project :
VCS ->Checkout from version control -> click github or git and paste your git url of the repository that you want to checkout 🙂 . Android studio will sync automatically if any dependency need to be resolved.

Git tutorial 2 ( Git Branching )

git
In our previous tutorial , we have learnt basics of git and how to create, commit and push to git . In this tutorial, we will learn about “Branching” and some other useful commands .

 

What is Git Branching :

Git doesn’t store only the new changes, but it stores a snapshot of the data on each commit. One commit object is created that contains a pointer to the snapshot of the content. If you have made 3 commits on the same branch, it looks something like below :

 

git-2-image1

 

Ok…so what is Git branching ?? Branch is simply a lightweight movable pointer to one of these commits. Default branch name is “master” in git. Everytime we commit new changes, it moves to the latest.

git-2-image2

 How does git know on which branch we are currently on ?? It keeps a pointer “HEAD” , that moves automatically if we checkout new branch.

git-2-image3

Let’s create one new branch “test”.

$ git branch test
 Currently we have two branches “master” and “testing” and we are on “master” . So HEAD will point to the “master” branch :

git-2-image4

 

 Checkout to branch “test” :

$ git checkout test
Now “HEAD” will point to the “testing” branch.

git-2-image5

 

Commit one new change on this “test” branch . ( As discussed in our previous tutorial)
 
Final view will be like :

git-2-image6

Now we have two branches “master” ,”test” and we have different commits on both of these branches.

In our last step, we will checkout back to the “master” branch, merge all changes from “test” branch to the master and finally delete this “test” branch.

//checkout back to master branch
$ git checkout master

//Merge changes in master: 
$ git checkout master
$ git merge test
 
//Delete test branch:
$ git branch -d hotfix

Some useful Commands :
//Check branch and branch pointers
$ git log --oneline --decorate

//To check history of commits from different branches
$ git log --oneline --decorate --graph --all

//To create a branch and switch to it at the same time
$ git checkout -b test

//This is shorthand for
$ git branch test 
$ git checkout test