Android AppBarLayout like Whatsapp Tutorial/Example

AppBarLayout is a vertical LinearLayout which implements various material design scrolling gestures.if you are not aware of Material Design refer here.

AppBarLayout children should provide scrolling behaviour by setScrollFlags(int) or in XML by app:layout_scrollFlags=””

Note: AppBarLayout depends heavily on being used as a direct child of Coordinator layout if you used with other ViewGroup its most of the scrolling functionality will not work.

So, Lets start:-

  1. Add following dependencies in build.gradle to work with AppBarLayout
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
  2. Create a layout containing AppBarLayout

activity_main.xml

<android.support.design.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"
    >
    <android.support.design.widget.AppBarLayout
         android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
      >
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            android:background="#6495ED"
            />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#6495ED"
            />
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        />
</android.support.design.widget.CoordinatorLayout>

app:layout_behavior describes the scroll behaviour of view pager it starts scroll below tab layout.

3.Now create a layout for fragment to show items

about.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

4. Now create a layout  for recyclerview items

listitems.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:gravity="center_vertical">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    card_view:cardCornerRadius="4dp"
    android:elevation="8dp"
    >
    <TextView
        android:id="@+id/itemname"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:padding="8dp"
        />
    </android.support.v7.widget.CardView>
</LinearLayout>

5.Now create a fragment and adapter for view pager

about.java

package com.coderzpassion.constitution.constitutionofindia;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by coderzpassion on 05/04/16.
 */
public class About extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        RecyclerView recyclerView=(RecyclerView) inflater.inflate(R.layout.about,container,false);
        setUpRecyclerView(recyclerView);
        return  recyclerView;
    }

    private void setUpRecyclerView(RecyclerView rv)
    {
        rv.setLayoutManager(new LinearLayoutManager(rv.getContext()));
        rv.setAdapter(new AboutUsAdapter(rv.getContext(), getListForItems()));
    }
    public ArrayList<String> getListForItems()
    {
        ArrayList<String> list =new ArrayList<>();
        list.add("First Item");
        list.add("Second Item");
        list.add("Third Item");
        list.add("Fourth Item");
        list.add("Fifth Item");
        list.add("Six Item");
        list.add("Seven Item");
        list.add("8 Item");
        list.add("9 Item");
        list.add("10 Item");
        list.add("11 Item");
        list.add("12 Item");
        list.add("13 Item");
        list.add("14 Item");
        list.add("15 Item");
        list.add("16 Item");
        list.add("17 Item");
        list.add("18 Item");
        list.add("19 Item");
        list.add("20 Item");
        list.add("21 Item");

        return list;
    }

    public  static class AboutUsAdapter extends RecyclerView.Adapter<AboutUsAdapter.ViewHolder>
    {
        ArrayList<String> aboutlist=new ArrayList<>();
        Context aboutuscontext;

             public static class ViewHolder extends RecyclerView.ViewHolder
             {
                 public final TextView items;
                public ViewHolder(View view)
                {
                    super(view);
                    items=(TextView)view.findViewById(R.id.itemname);
                }
             }

        public AboutUsAdapter(Context context,ArrayList<String> list)
        {
            aboutuscontext=context;
            aboutlist=list;

        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
           View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.listitems, parent, false);
            return  new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
                 holder.items.setText(aboutlist.get(position));
        }

        @Override
        public int getItemCount() {
            return aboutlist.size();
        }
    }
}

6.Now create a MainActivity and code for AppBarLayout

MainActivity.java

package com.coderzpassion.constitution.constitutionofindia;

import android.database.DataSetObserver;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(false);
        ViewPager viewPager=(ViewPager)findViewById(R.id.viewpager);
        if(viewPager!=null)
        {
            setUpViewPager(viewPager);
        }
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
       private void setUpViewPager(ViewPager viewPager)
        {
            Adapter adapter=new Adapter(getSupportFragmentManager());
            adapter.addFragment(new About(),"Article 1");
            adapter.addFragment(new About(),"Article 2");
            adapter.addFragment(new About(),"Article 3");

            viewPager.setAdapter(adapter);
           }
    @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_main, 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);
    }
    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

        public Adapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}

Output

appbarlayoutlikewhatsapp    workingwithappbarlayout    makingtoolbarlikewhatsapp

 

 

Android Material Design Tutorial/Example

Android Material Design was Introduced in Android Lollipop version. With Material Design Material theme, new widgets, new buttons like floating button and new animations are introduced.

Add this depency to your build.gradle

compile 'com.android.support:appcompat-v7:23.1.1'

In this tutorial, we will learn some basics of Material Design  Development

  1. Adding the Toolbar (ActionBar) to your application.

2. create layout for ActionBar and include it in your Activity’s Layout

3. change your styles.xml  to add a custom toolbar and  set parent Theme as  Theme.AppCompat.Light.NoActionBar as described below:-

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
       <!-- Customize your theme here. -->
    </style>

</resources>

4.Now Create layout for ActionBar

bar_layout.xml

<?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:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:id="@+id/toolbar"
    />

5. Include this ActionBar layout in MainActivity’s layout.

activity_main.xml

<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <include
       android:id="@+id/toolbar"
       layout="@layout/bar_layout"
       />

</RelativeLayout>

6. ActionBar items can be added by adding in menu_main.xml and there click can be handled by onOptionsItemSelected() method of MainActivity.java

7. Finally add ActionBar in MainActivity.java as Follows

MainActivity.java

package com.coderzpassion.recyclesample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar=(Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }

    @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_main, 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);
    }
}

Output

Screenshot_2016-02-28-16-25-27

2. Customization of Material Design Theme

  1. Materials design provides several attributes to change the color of theme.Lets take at look at them.
  2. colorPrimaryDark– This is the darkest primary color mainly applies to Notification Bar Background.
  3. colorPrimary- This is the Primary color which applies to toolbar(ActionBar) background.
  4. textColorPrimary- This is color of text which applies to toolbar title.
  5. windowBackground- This is background color of the application.
  6. navigationBarColor– This color is background footer of softbuttons.

Let’s Define Colors for Material Theme

  1. Open res->values->colors.xml. if u don’nt have colors.xml, create one with colors.xml name.
  2. Define Following Colors along with their name as follows.

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#537CED</color>
    <color name="colorPrimaryDark">#1410FB</color>
    <color name="textColorPrimary">#000000</color>
    <color name="windowBackground">#5B5F69</color>
    <color name="navigationBarColor">#000000</color>
</resources>

3. Now Create theme in styles.xml from res->values->styles.xml to use these colors.

styles.xml

<resources>

    <style name="CustomMaterialTheme" parent="CustomMaterialTheme.Base">

    </style>

    <style name="CustomMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="android:textColorPrimary">@color/textColorPrimary</item>
        <item name="android:windowBackground">@color/windowBackground</item>     
    </style>

</resources>

4. For Creating designs specifically for Android Lollipop create a folder named values-v21 under res->values-v21. Under values-v21 create styles.xml as follows

styles.xml

<resources>

    <style name="CustomMaterialTheme" parent="CustomMaterialTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>

</resources>

5. Now we are done with creating Custom Material Theme. Now set the theme to application in AndroidMainfest as follows.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzpassion.recyclesample" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/CustomMaterialTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output

Screenshot_2016-02-28-17-08-54