Monday, 3 April 2017

Bottom Navigation View Example

            When a requirement to implement Bottom Navigation View, in this tutorial we will see how to implement Bottom Navigation View. BottomNavigationView is a widget, Google introduced Material Design Support Library v25. It's looks similar to TabLayout, but the implementation is lot of difference.

Screen Shots:






Download Source Code 


1. Build Gradle 
    To Start this example we need to include following dependencies in our build.gradle file.check the below build.gradle file.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.prasad.bottomnavigationbar"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-vector-drawable:25.1.0'
    testCompile 'junit:junit:4.12'
}

2. Menu 
     For displaying items into an bottom navigation bar, a menu type XML file is used. This XML contains minimum three attributes(id, icon, title). for this create a new menu file with name navigation.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/title_home" />

    <item
        android:id="@+id/navigation_dashboard"
        android:icon="@drawable/ic_dashboard_black_24dp"
        android:title="@string/title_dashboard" />

    <item
        android:id="@+id/navigation_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/title_notifications" />

</menu>

3. XML Layout 
    Open activity_main.xml layout and change the modifications as below layout in your layout.

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.prasad.bottomnavigationbar.MainActivity">

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/navigation" />

</LinearLayout>

This example contains three fragments which could be switched by Bottom Navigation View. so we need to create three fragment layouts.
 create a new layout with name as home_fragment, do the changes as below layout.

home_fragment.xml: 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:gravity="center_vertical"
        android:text="Home Fragment"
        android:textSize="30sp" />
</LinearLayout>

 create a new layout with name as dashboard_fragment, do the changes as below layout.

dashboard_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:gravity="center_vertical"
        android:text="Dashboard Fragment"
        android:textSize="30sp" />
</LinearLayout>

 create a new layout with name as notifications_fragment, do the changes as below layout.

notifications_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:gravity="center_vertical"
        android:text="Notifications Fragment"
        android:textSize="30sp" />
</LinearLayout>

4. Java Classes
     Open MainActivity.java class and do the changes like below.
 
    MainActivity.java
package com.prasad.bottomnavigationbar;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            Fragment selectedFragment = null;

            switch (item.getItemId()) {
                case R.id.navigation_home:
                    selectedFragment = HomeFragment.newInstance();
                    break;
                case R.id.navigation_dashboard:
                    selectedFragment = DashboardFragment.newInstance();
                    break;
                case R.id.navigation_notifications:
                    selectedFragment = NotificationsFragment.newInstance();
                    break;
            }

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.frame_layout, selectedFragment);
            transaction.commit();

            return true;
        }

    };

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

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        //first fragment - one time only
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout, HomeFragment.newInstance());
        transaction.commit();

        //Used to select an item programmatically
        //bottomNavigationView.getMenu().getItem(2).setChecked(true);
    }

}

    Create three fragment classes for fetching fragment layouts.

    HomeFragment.java
package com.prasad.bottomnavigationbar;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;



public class HomeFragment extends Fragment {

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.home_fragment, container, false);
    }
}

    DashboardFragment.java
package com.prasad.bottomnavigationbar;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class DashboardFragment extends Fragment {

    public static DashboardFragment newInstance() {
        DashboardFragment fragment = new DashboardFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dashboard_fragment, container, false);
    }
}

    NotificationsFragment.java
package com.prasad.bottomnavigationbar;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;



public class NotificationsFragment extends Fragment {

    public static NotificationsFragment newInstance() {
        NotificationsFragment fragment = new NotificationsFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.notifications_fragment, container, false);
    }

}

    5. Android Manifest

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <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>


12 comments:

  1. Were a gaggle of volunteers as well as starting off a brand new gumption within a community. Your blog furnished us precious details to be effective on. You've got completed any amazing work!
    Were a gaggle of volunteers as well as starting off a brand new gumption within a community. Your blog furnished us precious details to be effective on. You've got completed any amazing work!

    ReplyDelete
  2. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in velachery| rpa training in tambaram |rpa training in sholinganallur | rpa training in annanagar| rpa training in kalyannagar

    ReplyDelete
  3. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    Data Science training in kalyan nagar | Data Science training in OMR

    Data Science training in chennai | Data science training in velachery

    Data science training in tambaram | Data science training in jaya nagar

    ReplyDelete
  4. How to stop smoking weed ???

    1.Do you want to know How to stop smoking weed or have you been wondering of how to get your dear one to stop smoking weed ?
    Every weed smoker knows deep down that quitting the behavior is an uphill task. And some people don`t know How to quit smoking weed .. They should
    Know How to quit smoking weed by visiting in this https://irvined.co.uk/ website.

    2.Long-term marijuana users may find the withdrawal experience uncomfortable. Marijuana detox helps one to slowly ease off of THC
    until it is completely eliminated from the body system. Marijuana detox also helps to reduce withdrawal symptoms thus making it
    easier for even highly addicted individuals to make full about turn in their weed smoking habits (avoiding relapse).

    3.The decision to stop smoking weed is usually impulsive for many individuals. If you have smoked pot long enough, you probably have plenty of memories
    where you did something and swore to yourself to stop your weed smoking habit going forward. And if you don`t know How to stop smoking pot ...
    Then visit https://irvined.co.uk/ here to know more.

    4.Quitting marijuana will give you the chance to become more responsible and set you in the right direction to progress in your life.
    And the good thing is that you don’t have to try quitting on your own now. ‘ Quit Marijuana The Complete Pack ’ is just a click away at a very affordable price.
    See more details about the guide and current purchase offers at https://quit-weed.com/. You can do this. Regardless of how long you have smoked pot or used marijuana
    in other ways, the quit marijuana pack offers you robust support to ensure that you achieve your goals. To know more information visit https://irvined.co.uk/ here.

    ReplyDelete
  5. Big Truck Tow: Heavy Duty towing service san jose

    We're rated the most reliable heavy duty towing san jose service & roadside assistance in San Jose!
    Call us now! We're ready to help you NOW!

    Since 1999, tow truck san jose has provided quality services to clients by providing them
    with the professional care they deserve. We are a professional and affordable Commercial
    Towing Company. BIG TRUCK TOW provides a variety of services, look below for the list of
    services we offer. Get in touch today to learn more about our heavy duty towing


    Click here to Find tow truck near me

    ReplyDelete
  6. Keto Pills The Fastest Way to Get Into Ketosis?
    Keto diet pills reviews to let you know how to get into ketosis fast and feel
    young & energetic. These keto diet pills work wonders when taken as advised.
    Read This Informative article from top to bottom about Best Keto diet pills reviews & See
    Keto pills can help you to get into ketogenesis quickly and enjoy life-long benefits of
    maintaining healthy weight.our amazing Keto Diet Pills Recommendation at the end!
    How to get into ketogenesis ?
    If you Don’t know Where to buy keto diet pills click here.
    To Know More Information Click https://ketodietpillsinfo.com/ here.

    ReplyDelete
  7. ez battery reconditioning reviews - How to Recondition a battery .

    ez battery reconditioning reviews - You can now easily revive your old batteries with
    this ez battery reconditioning pdf which provides step by step instructions ... for How to recondition a battery

    For more information Visit https://ezbatteryreconditioninginfo.com/ here .


    ReplyDelete
  8. ترفند برد و آموزش بازی انفجار آنلاین و شرطی، نیترو بهترین و پرمخاطب ‌ترین سایت انفجار ایرانی، نحوه برد و واقعیت ربات ها و هک بازی انجار در
    اینجا بخوانید
    کازینو آنلاین نیترو
    بازی حکم آنلاین نیترو
    بازی حکم آنلاین
    Introducing the Nitro Blast game site
    معرفی سایت بازی انفجار نیترو
    همان طور که می دانید بازی های کازینو های امروزه از محبوبیت ویژه ای برخودارند که این محبوبیت را مدیون سایت های شرط می باشند. با گسترش اینترنت این بازی ها محدودیت های مکانی و زمانی را پشت سرگذاشته و به صورت آنلاین درآمده اند.
    بازی انفجار نیترو
    بازی انفجار
    یکی از محبوب ترین بازی های کازینو، بازی انفجار می باشد که ساخته سایت های شرط بندی می باشد و امروزه از طرفداران ویژه ای برخودار است. با گسترش اینترنت سایت های شرط بندی مختلفی ایجاد شده اند که این بازی را به صورت آنلاین ساپورت می کنند. یکی از این سایت ها، سایت معتبر نیترو می باشد. در این مقاله قصد داریم به معرفی
    سایت بازی انفجار نیترو بپردازیم.
    سایت پیش بینی فوتبال نیتر
    سایت پیش بینی فوتبال
    بازی رولت نیترو
    کازینو آنلاین

    Visit https://www.wmsociety.org/
    here for more information

    ReplyDelete
  9. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.
    Best CBD Oil UK

    ReplyDelete
  10. Compre documentos en línea, documentos originales y registrados.
    Acerca de Permisodeespana, algunos dicen que somos los solucionadores de problemas, mientras que otros se refieren a nosotros como vendedores de soluciones. Contamos con cientos de clientes satisfechos a nivel mundial. Hacemos documentos falsos autorizados y aprobados como Permiso de Residencia Español, DNI, Pasaporte Español y Licencia de Conducir Española. Somos los fabricantes y proveedores de primer nivel de estos documentos, reconocidos a nivel mundial.

    Comprar permiso de residencia,
    permiso de residenciareal y falso en línea,
    Compre licencia de conducir en línea,
    Compre una licencia de conducir española falsa en línea,
    Comprar tarjeta de identificación,
    Licencia de conducir real y falsa,
    Compre pasaporte real en línea,

    Visit Here fpr more information. :- https://permisodeespana.com/licencia-de-conducir-espanola/
    Address: 56 Guild Street, London, EC4A 3WU (UK)
    Email: contact@permisodeespana.com
    WhatsApp: +443455280186

    ReplyDelete

Spinner example using AppCompatSpinner widget

          When we have a requirement to use spinner(drop down) to show list of objects in your application. Here we will see how to use Ap...