• Solo Great Sale

    Solo Great Sale Powered By Circle Card 2015

  • Solo Great Sale

    Solo Great Sale Powered By Circle Card 2015

  • Oracle Java Magazine

    As Cover of Oracle Java Magazine March/April 2012 issue

  • Launching jDuchess Indonesia

    Gunadarma University 2011

    www.jduchess.or.id

  • Launching jDuchess Indonesia

    Gunadarma University 2011

    www.jduchess.or.id

  • Launching Java 7

    Binus University 2011

  • Eclipse Democamp

    Microsoft Indonesia 2011

  • Oracle Academy

    SMK PGRI 3 Malang 2010

  • Launching JENI 2.0

    ITB Bandung 2012

  • Oracle Academy

    SMK PGRI 3 Malang 2010

  • Java and Android Roadshow

    SMK PGRI 3 Malang 2012

  • Oracle Academy

    SMK PGRI 3 Malang 2010

  • Launching JENI 2.0

    ITB Bandung 2012

  • Oracle Academy

    SMK PGRI 3 Malang 2011

  • Java and Android Roadshow

    SMK Plus Darussalam Kediri 2012

  • Oracle Academy Seminar

    LIKMI Bandung, 2012

  • Oracle Academy Seminar

    Indonesia University, 2012

  • Seminar Android

    Universitas Budi Luhur 2010

  • Java and Android Roadshow

    SMK Hasan Kafrawi Jepara 2012

  • Sosialisasi Kurikulum 2013

    LPMP Surabaya 2013

  • IOSA

    Indonesia Open Source Award 2011

  • Java Training

    SMKN 02 Sukabumi 2010

  • Sosialisasi Kurikulum

    SMKN 01 Tulungagung 2011

  • Sosialisasi Kurikulum 2013

    LPMP Surabaya 2013

Saturday, December 7, 2013

Posted by Netty Herawaty
| 12:25 PM
Satu tahun yang lalu saya pernah membahas tentang Android Dashboard. Silahkan dilihat disini . Nah sekarang dashboard sudah digeser dengan UI pattern untuk sliding menu yang baru diperkenalkan Google yang bernama "Navigation Drawer".

Sejak Google memperkenalkan Navigation Drawer, kita mulai banyak menemukan aplikasi mobile apps Android yang menggunakan "hamburger" style ini. 

Navigation Drawer ini letaknya disembunyikan dan dapat dilihat dengan menggeser screen dari kiri atau dengan menekan button "hamburger" dan app icon di action bar. Perhatikan contoh sliding menu yang ada di Facebook dan Google Play Store berikut ini

                               

Nah sekarang kita akan membuat sliding menu yang menyerupai contoh diatas

Membuat Project Baru

1. Download "hamburger" icon

Download "hamburger" icon dan simpan pada res/drawable

2. Membuat project baru

Buat project baru dari File > New > Android Application Project


3. Membuat String variable

Buka strings.xml pada folder res/value dan tambahkan array item untuk navigation drawer
<?xml version="1.0" encoding="utf-8"?>

<resources>


    <string name="app_name">Navigation Drawer</string>

    <string name="action_settings">Settings</string>

    <string name="hello_world">Hello world!</string>

    <string name="drawer_open">Slider Menu Opened</string>

    <string name="drawer_close">Slider Menu Closed</string>

    
    <!-- Nav Drawer Menu Items -->

    <string-array name="nav_drawer_items">

        <item >Home</item>

        <item >Directory</item>

        <item >Promotion</item>

        <item >Event</item>

        <item >Voucher</item>

        <item >My Account</item>

        <item >Logout</item>

    </string-array>


    <!-- Nav Drawer List Item Icons -->

    <!-- Keep them in order as the titles are in -->

    <array name="nav_drawer_icons">

        <item>@drawable/icon_home</item>

        <item>@drawable/icon_directory</item>

        <item>@drawable/icon_promo</item>

        <item>@drawable/icon_event</item>

        <item>@drawable/icon_voucher</item>

        <item>@drawable/icon_myaccount</item>

        <item>@drawable/icon_logout</item>

    </array>
    

    <!-- Content Description -->

    <string name="desc_list_item_icon">Item Icon</string>


</resources>

4. Membuat DrawerLayout

UI element untuk navigation drawer adalah DrawerLayout. tambahkan kode berikut pada activity_main.xml di folder res/layout. FrameLayout untuk menampilkan Fragment dan ListView untuk menampilkan slider menu
<android.support.v4.widget.DrawerLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/drawer_layout"

    android:layout_width="match_parent"

    android:layout_height="match_parent">


    <!-- Framelayout to display Fragments -->

    <FrameLayout

        android:id="@+id/frame_container"

        android:layout_width="match_parent"

        android:layout_height="match_parent" />


    <!-- Listview to display slider menu -->

    <ListView

        android:id="@+id/list_slidermenu"

        android:layout_width="280dp"

        android:layout_height="match_parent"

        android:layout_gravity="start"

        android:choiceMode="singleChoice"

        android:divider="@color/list_divider"

        android:dividerHeight="1dp"      

        android:listSelector="@drawable/list_selector"

        android:background="@color/list_background"/>

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

Membuat Layout Custom ListView

Untuk membuat custome listview kita membutuhkan Adapter class dan custom layout untuk masing-masing list item pada listview. Sebelum kita membuat Adapter class, kita persiapkan dulu kebutuhan layout nya.

5. Membuat State ListItem

Kita membutuhkan 4 file xml, 2 file xml untuk membuat 2 state list item, yaitu ketika normal state dan pressed state atau ketika list item ditekan dan 1 file xml untuk menggabungkan keduanya (list selector) dan 1 file untuk membuat counter background

a. Normal State
Buat xml file di dalam res/drawable dan beri nama list_item_bg_normal.xml (jika belum tersedia folder drawable, silahkan create new folder dan beri nama drawable)
<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">

  <gradient

      android:startColor="@color/list_background"

      android:endColor="@color/list_background"

      android:angle="90" />

</shape>

b. Pressed State
Buat xml file di dalam res/drawable dan beri nama list_item_bg_pressed.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">

  <gradient

      android:startColor="@color/list_background_pressed"

      android:endColor="@color/list_background_pressed"

      android:angle="90" />

</shape>

c. List Selector
Buat xml file di dalam res/drawable dan beri nama list_selector.xml
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">


    <item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/>

    <item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>

    <item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/>


</selector>

d. Counter Background
Buat xml file di dalam res/drawable dan beri nama counter_bg.xml
<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle" >


    <!-- view background color -->

    <solid android:color="@color/counter_text_bg" >

    </solid>


    <!-- If you want to add some padding -->

    <padding

        android:right="3dp"

        android:left="3dp" >

    </padding>


    <!-- Here is the corner radius -->

    <corners android:radius="2dp" >

    </corners>

</shape>

Sampai disini pasti layout yang kalian buat banyak yang error, karena kita belum menambahkan file xml untuk menampung color atau warna-warna yang kita gunakan pada listview. Color ini harus diletakkan di dalam res/values

e. Color
Buat xml file di dalam res/values dan beri nama color.xml
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <color name="list_item_title">#000000</color>

    <color name="list_background">#FAFAFA</color>

    <color name="list_background_pressed">#55AADC</color>

    <color name="list_divider">#272727</color>

    <color name="counter_text_bg">#626262</color>

    <color name="counter_text_color">#FFFFFF</color>

</resources>

6. Membuat Layout Drawer ListItem

Buat xml file di dalam res/layout dan beri nama drawer_list_item.xml Drawer ListItem ini unuk mendefinisikan masing-masing list row. RelativeLayout yang ada di file ini berisi title, icon dan counter listview
<?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="48dp"

    android:background="@drawable/list_selector">



    <ImageView

        android:id="@+id/icon"

        android:layout_width="25dp"

        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"

        android:layout_marginLeft="12dp"

        android:layout_marginRight="12dp"

        android:contentDescription="@string/desc_list_item_icon"

        android:src="@drawable/icon_home"

        android:layout_centerVertical="true" />



    <TextView

        android:id="@+id/title"

        android:layout_width="wrap_content"

        android:layout_height="match_parent"

        android:layout_toRightOf="@id/icon"

        android:minHeight="?android:attr/listPreferredItemHeightSmall"

        android:textAppearance="?android:attr/textAppearanceListItemSmall"

        android:textColor="@color/list_item_title"

        android:gravity="center_vertical"

        android:paddingRight="40dp"/>


    <TextView android:id="@+id/counter"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:background="@drawable/counter_bg"

        android:layout_alignParentRight="true"

        android:layout_centerVertical="true"

        android:layout_marginRight="8dp"

        android:textColor="@color/counter_text_color"/>


</RelativeLayout>

Membuat Class Custom ListView

Masing-masing list item berisi title, icon dan counter. Jadi kita membuat model untuk merepresentasikan ketiga elemen tersebut

7. Buat Model DrawerItem

Buat package baru untuk meletakkan class model. Package saya com.netyherawaty.slidingmenu.model
Buat class NavDrawerItem.java dan tambahkan kode berikut
package com.netyherawaty.slidingmenu.model;



public class NavDrawerItem {



  private String title;

  private int icon;

  private String count = "0";

  // boolean to set visiblity of the counter

  private boolean isCounterVisible = false;



  public NavDrawerItem() {

  }



  public NavDrawerItem(String title, int icon) {

    this.title = title;

    this.icon = icon;

  }



  public NavDrawerItem(String title, int icon, boolean isCounterVisible,

      String count) {

    this.title = title;

    this.icon = icon;

    this.isCounterVisible = isCounterVisible;

    this.count = count;

  }



  public String getTitle() {

    return this.title;

  }



  public int getIcon() {

    return this.icon;

  }



  public String getCount() {

    return this.count;

  }



  public boolean getCounterVisibility() {

    return this.isCounterVisible;

  }



  public void setTitle(String title) {

    this.title = title;

  }



  public void setIcon(int icon) {

    this.icon = icon;

  }



  public void setCount(String count) {

    this.count = count;

  }



  public void setCounterVisibility(boolean isCounterVisible) {

    this.isCounterVisible = isCounterVisible;

  }

}

8. Membuat Adapter DrawerItem

Buat package baru untuk meletakkan class adapter. Package saya com.netyherawaty.slidingmenu.adapter Buat class NavDrawerListAdapter.java dan tambahkan kode berikut
package com.netyherawaty.slidingmenu.adapter;



import java.util.ArrayList;



import com.netyherawaty.slidingmenu.R;

import com.netyherawaty.slidingmenu.model.NavDrawerItem;



import android.app.Activity;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.ImageView;

import android.widget.TextView;



public class NavDrawerListAdapter extends BaseAdapter {

 

  private Context context;

  private ArrayList<NavDrawerItem> navDrawerItems;

 

  public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){

    this.context = context;

    this.navDrawerItems = navDrawerItems;

  }



  @Override

  public int getCount() {

    return navDrawerItems.size();

  }



  @Override

  public Object getItem(int position) {  

    return navDrawerItems.get(position);

  }



  @Override

  public long getItemId(int position) {

    return position;

  }



  @Override

  public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {

            LayoutInflater mInflater = (LayoutInflater)

                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            convertView = mInflater.inflate(R.layout.drawer_list_item, null);

        }

        

        ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);

        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);

        TextView txtCount = (TextView) convertView.findViewById(R.id.counter);

        

        imgIcon.setImageResource(navDrawerItems.get(position).getIcon());       

        txtTitle.setText(navDrawerItems.get(position).getTitle());

       

        if(navDrawerItems.get(position).getCounterVisibility()){

          txtCount.setText(navDrawerItems.get(position).getCount());

        }else{

          txtCount.setVisibility(View.GONE);

        }

       

        return convertView;

  }



}

9. Update class MainActivity

tambahkan kode berikut pada class MainActivity.java
package com.netyherawaty.slidingmenu;



import java.util.ArrayList;



import com.netyherawaty.slidingmenu.adapter.NavDrawerListAdapter;

import com.netyherawaty.slidingmenu.model.NavDrawerItem;



import android.os.Bundle;

import android.app.Activity;

import android.app.Fragment;

import android.app.FragmentManager;

import android.content.res.Configuration;

import android.content.res.TypedArray;

import android.support.v4.app.ActionBarDrawerToggle;

import android.support.v4.widget.DrawerLayout;

import android.util.Log;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ListView;



public class MainActivity extends Activity {



  private DrawerLayout mDrawerLayout;

  private ListView mDrawerList;

  private ActionBarDrawerToggle mDrawerToggle;

  private CharSequence mDrawerTitle;

  private CharSequence mTitle;

  private String[] navMenuTitles;

  private TypedArray navMenuIcons;



  private ArrayList<NavDrawerItem> navDrawerItems;

  private NavDrawerListAdapter adapter;



  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);



    mTitle = mDrawerTitle = getTitle();

   

    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);



    navMenuIcons = getResources()

        .obtainTypedArray(R.array.nav_drawer_icons);



    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);



    navDrawerItems = new ArrayList<NavDrawerItem>();



    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));

    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));

    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1), true, "5"));

    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "2"));

    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1), true, "12"));

    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));

    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(6, -1)));

   

    navMenuIcons.recycle();



    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

   

    adapter = new NavDrawerListAdapter(getApplicationContext(),

        navDrawerItems);

    mDrawerList.setAdapter(adapter);



    getActionBar().setDisplayHomeAsUpEnabled(true);

    getActionBar().setHomeButtonEnabled(true);



    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,

        R.drawable.ic_drawer,

        R.string.app_name,

        R.string.app_name

    ) {

      public void onDrawerClosed(View view) {

        getActionBar().setTitle(mTitle);

        invalidateOptionsMenu();

      }



      public void onDrawerOpened(View drawerView) {

        getActionBar().setTitle(mDrawerTitle);

        invalidateOptionsMenu();

      }

    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);



    if (savedInstanceState == null) {

      displayView(0);

    }

  }



  private class SlideMenuClickListener implements

      ListView.OnItemClickListener {

    @Override

    public void onItemClick(AdapterView<?> parent, View view, int position,

        long id) {

      displayView(position);

    }

  }



  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);

    return true;

  }



  @Override

  public boolean onOptionsItemSelected(MenuItem item) {

    if (mDrawerToggle.onOptionsItemSelected(item)) {

      return true;

    }

    switch (item.getItemId()) {

    case R.id.action_settings:

      return true;

    default:

      return super.onOptionsItemSelected(item);

    }

  }



  @Override

  public boolean onPrepareOptionsMenu(Menu menu) {

    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);

    menu.findItem(R.id.action_settings).setVisible(!drawerOpen);

    return super.onPrepareOptionsMenu(menu);

  }



  private void displayView(int position) {

    // update the main content by replacing fragments

    Fragment fragment = null;

    switch (position) {

    case 0:

      fragment = new HomeFragment();

      break;

    case 1:

      fragment = new DirectoryFragment();

      break;

    case 2:

      fragment = new PromotionFragment();

      break;

    case 3:

      fragment = new EventFragment();

      break;

    case 4:

      fragment = new VoucherFragment();

      break;

    case 5:

      fragment = new MyAccountFragment();

      break;

    case 6:  

      break; 

     

    default:

      break;

    }



    if (fragment != null) {

      FragmentManager fragmentManager = getFragmentManager();

      fragmentManager.beginTransaction()

          .replace(R.id.frame_container, fragment).commit();



      mDrawerList.setItemChecked(position, true);

      mDrawerList.setSelection(position);

      setTitle(navMenuTitles[position]);

      mDrawerLayout.closeDrawer(mDrawerList);

    } else {

      Log.e("MainActivity", "Error in creating fragment");

    }

  }



  @Override

  public void setTitle(CharSequence title) {

    mTitle = title;

    getActionBar().setTitle(mTitle);

  }



  @Override

  protected void onPostCreate(Bundle savedInstanceState) {

    super.onPostCreate(savedInstanceState);

    mDrawerToggle.syncState();

  }


  @Override

  public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);

    mDrawerToggle.onConfigurationChanged(newConfig);

  }

}

Sampai disini Anda akan menemukan error di bagian kode berikut
  private void displayView(int position) {

    // update the main content by replacing fragments

    Fragment fragment = null;

    switch (position) {

    case 0:

      fragment = new HomeFragment();

      break;

    case 1:

      fragment = new DirectoryFragment();

      break;

    case 2:

      fragment = new PromotionFragment();

      break;

    case 3:

      fragment = new EventFragment();

      break;

    case 4:

      fragment = new VoucherFragment();

      break;

    case 5:

      fragment = new MyAccountFragment();

      break;

    case 6:  

      break; 

    default:

      break;

    }

Kode diatas adalah sebagai handling navigation ketika salah satu sliding menu di klik. Jadi buatlah class dan layout untuk menu Home, Directory, Promotion, Event, Voucher dan MyAccount. Saya beri contoh untuk class dan layout menu Voucher.

10. Membuat Fragment View

Buatlah class baru dengan nama VoucherFragment.java dan tambahkan kode berikut
package com.netyherawaty.slidingmenu;

import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;
public class VoucherFragment extends Fragment {


      public VoucherFragment(){}

      @Override

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


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

          return rootView;

      }

}

Kemudian untuk layoutnya buat file xml dengan nama fragment_voucher.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/txtLabel"

         android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:textSize="16dp"

        android:text="Voucher View"/>


    <ImageView android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/txtLabel"

        android:src="@drawable/icon_voucher"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="10dp"/>

</RelativeLayout>

Lakukan hal yang sama untuk menu lain. Perhatikan struktur project yang sudah kita buat sampai saat ini



Sekarang run project, klik pada hamburger icon dan navigation drawer akan tampil seperti gambar dibawah ini.


Ketika di klik pada menu Voucher, maka akan tampil fragment layout yang telah kita buat di langkah no 10 dan navigation drawer akan hilang (hidden)



Reactions: