Saturday 27 August 2016

Build Menu Navigation Drawer Android


Android Menu Navigation Drawer

Hello world. Its night to build something little android project and i hope in the future it will be big project for all tricks or tutorial about android project. From now i will create a tutorial on this project. Its mean, for all tutorial will do on this project. And also i will post to my Github page. So you can post comment on my Github page or on my post by post. If you still confused about structure android project you can read on my post, this one.

For first post, i share about Navigation Drawer android. It's a something like menu navigation on android apps. On the navigation drawer, i do interaction one activity and many fragment. Lets do it.

First Activity, i have xml file and one activity. So this is my xml file, i call it activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

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

As you can see, on this my xml file i have DrawerLayout, NavigationView, FragmentLayout, and Include. This file will be first show when app run. So we set first User Interface and Navigator User Interface. Include is another my xml file is app_bar_main. First UI it will will show like this. 


First UI Xml File



This is my app_bar_main.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.blogspot.dedyyuristiawan.androidstudioproject.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

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

On this file, i have CoordinatorLayout, AppBarLayout ( for put Toolbar) , and FloatingActionButton. This file it will be fist UI when you run app for first time. So for Navigation UI i put on the another xml file. Its Item menu on the folder menu, i call it activity_main_drawer.xml.

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

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/fragmentOne"
            android:icon="@drawable/ic_menu_camera"
            android:title="Fragment One" />
        <item
            android:id="@+id/fragmentTwo"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Fragment Two" />
        <item
            android:id="@+id/fragmentThree"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Fragment Three" />
        <item
            android:id="@+id/fragmentFour"
            android:icon="@drawable/ic_menu_manage"
            android:title="Fragment Four" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/fragmentFive"
                android:icon="@drawable/ic_menu_share"
                android:title="Fragment Five" />
            <item
                android:id="@+id/fragmentQuit"
                android:icon="@drawable/ic_menu_send"
                android:title="Quit" />
        </menu>
    </item>

</menu>

So i have a lot item menu for navigation. and i have group for make different. It will be show like this.


Navigation UI


On this navigation, i put on the top is a header navigation and i write on this file xml. I call it nav_header_main.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="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>

As you can see, i've Image and two text_view. You can imagine with Navigation UI Screen. And then as i told you before, i have activity and fragment. Navigation menu work on the one activity and a lot fragment. Its certain. This is my activity, i call it MainActivity.java. On this file will build work with xml, and make it happen like first UI. This is MainActivity.java. 

package com.blogspot.dedyyuristiawan.androidstudioproject;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar toolbar;
    private Fragment fragment = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setToolbar();
        showFAB();
        setDraawerLayout();
        setNavigation();
        setFirstFragment();
    }

    //function for set first fragment run
    private void setFirstFragment(){
        Fragment fragment = null;
        fragment = new FragmentOne();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();
    }

    //private void set navigation
    private void setNavigation(){
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    // function to set drawer layout
    private void setDraawerLayout(){
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
    }

    // function to set toolbar
    private void setToolbar(){
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    //function to call fab
    private void showFAB(){
        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();
            }
        });
    }

    // function to detect back button, when user click button back
    // it will close drawer
    // and close app
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    //function for create menu, on the left top tollbar
    // it declare from xml menu, folder menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    // function to create action click when user click menu on the menu folder
    // you can check on the menu folder
    @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);
    }

    // function to create action click when user click navigation menu item
    // id it from menu folder
    // and also will change one fragment to another fragment, with replace
    // after change fargment will close drawer too
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        int id = item.getItemId();
        //declare fragment
        Fragment fragment = null;

        //select fragment with id condition
        //set tittle bar
        //call fragment
        if (id == R.id.fragmentOne) {
            Log.d("fragmentOne Test","Works" );
            getSupportActionBar().setTitle(R.string.fragmentOne);
            fragment = new FragmentOne();

        } else if (id == R.id.fragmentTwo) {
            Log.d("fragmentTwo Test","Works" );
            getSupportActionBar().setTitle(R.string.fragmentOne);
            fragment = new FragmentOne();

        } else if (id == R.id.fragmentThree) {
            Log.d("fragmentThree Test","Works" );
            getSupportActionBar().setTitle(R.string.fragmentOne);
            fragment = new FragmentOne();

        } else if (id == R.id.fragmentThree) {
            Log.d("fragmentThree Test","Works" );
            getSupportActionBar().setTitle(R.string.fragmentOne);
            fragment = new FragmentOne();

        } else if (id == R.id.fragmentFour) {
            Log.d("fragmentFour Test","Works" );
            getSupportActionBar().setTitle(R.string.fragmentOne);
            fragment = new FragmentOne();

        } else if (id == R.id.fragmentFive) {
            Log.d("fragmentFive Test","Works" );
            getSupportActionBar().setTitle(R.string.fragmentOne);
            fragment = new FragmentOne();

        } else if (id == R.id.fragmentQuit){
            Log.d("fragmentQuit Test","Works" );
            getSupportActionBar().setTitle(R.string.fragmentOne);
            finish();
        }

        //interaction fragment, with replace
        //close navigator
        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);

        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        }

        return true;
    }
}

On this file, i've to write comment on the function to so you can learn and understand it. The important is on the top function is a onCreate(Bundle savedInstanceState) . Its first function when app run. After that will call another function like this. 

setToolbar();
        showFAB();
        setDraawerLayout();
        setNavigation();
        setFirstFragment();

simple right? there is another java file, it's a fragment file. As you can see, activity will be make interaction with fragment see on the onNavigationItemSelected function. I can replace it with another function. But i create one fragment. haha its ok, you can create yourself. So this is my fragment class.

package com.blogspot.dedyyuristiawan.androidstudioproject;

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

/**
 * Created by dedyyuristiawan on 8/27/16.
 */
public class FragmentOne extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_one, container, false);

        return rootView;
    }
}

As you can see, on my fragment have xml too. And this is my xml file. I call it fragment_one.xml.

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


    <TextView
        android:id="@+id/tvOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:text="Hello World!"
        android:layout_centerInParent="true"/>

    <TextView
        android:id="@+id/txtLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvOne"
        android:layout_centerInParent="true"
        android:textSize="16dp"
        android:text="@string/fragmentOne"/>

</RelativeLayout>

That's it. Android Navigator Apps. If you still have confuse about my code you can fill comment bellow, or just sent email to me (bellow my photo). Remember it will change when i write post. Cause all tutorial i will create on this project. If you want to see about previous code, you can search on the commit Github Page. And this is my project, Just download it on my Github page

Github page.

Share:
Lokasi: Cilandak, South Jakarta City, Special Capital Region of Jakarta, Indonesia

0 komentar:

Post a Comment


<br>


Advice for contacting me at dedyy54@gmail.com