Sabtu, 23 Agustus 2014

Membuat Aplikasi Android dengan Navigasi Tab, ActionBar Tabs

Membuat Aplikasi Android dengan Navigasi Tab, ActionBar Tabs ini, seperti halnya pada artikel serupa yaitu Membuat Aplikasi Android dengan Navigasi Swipe dan Tabs, digenerate dari Eclipse ADT versi Build: v21.0.0-531062 dengan SDK versi Jelly Beans. Jadi jangan heran jika project yang anda generate dengan cara yang sama bisa saja hasilnya sedikit berbeda karena Eclipse atau Android Developer Tools yang and gunakan mungkin versinya berbeda dengan yang digunakan di artikel ini.
Project ini menggunakan ViewPager bertipe Tab dan Fragment, sehingga dalam satu Activity bisa ada beberapa tampilan Fragment Layout.

Langkah pertama buat dahulu project baru dengan Navigasi Tab. Pada langkah menentukan Minimum Required SDK pilih Honeycomb 3.0 karena jika dibawah itu tidak bisa menggunakan Navigasi Tab.



Kemudian pada langkah memilih tipe Navigasi pilih Tabs.


Kemudian buat desain halaman utama pada file res/layout/activity_main.xml sebagai berikut :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="MergeRootFrame" />

Kemudian tambahkan file XML Layout baru pada direktory res/layout dengan nama fragment_main.xml sebagai berikut :

<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="wrap_content" android:text="Fragment Main" /> <Button android:id="@+id/btnone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="One" /> </LinearLayout>

Kemudian tambahkan lagi file Layout XML baru pada direktory res/layout dengan nama fragment_one.xml sebagai berikut :

<?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:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fragment One" /> <Button android:id="@+id/btntwo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Two" /> </LinearLayout>

Kemudian tambahkan lagi file Layout XML baru pada direktory res/layout dengan nama fragment_two.xml sebagai berikut :

<?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:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment Two" />

    <Button
        android:id="@+id/btnmain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Main" />

</LinearLayout>

Kemudian buka file MainActivity.java tambahkan kode program berikut ini :

package com.amijaya.android_tabs_navigation; import android.app.ActionBar; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; //http://cariprogram.blogspot.com //nuramijaya@gmail.com public class MainActivity extends FragmentActivity implements ActionBar.TabListener { /** * The serialization (saved instance state) Bundle key representing the * current tab position. */ private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item"; Button btnone; Button btntwo; Button btnmain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar to show tabs. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // For each of the sections in the app, add a tab to the action bar. actionBar.addTab(actionBar.newTab().setText("Main") //R.string.title_section1) .setTabListener(this)); actionBar.addTab(actionBar.newTab().setText("One") //R.string.title_section2) .setTabListener(this)); actionBar.addTab(actionBar.newTab().setText("Two") //R.string.title_section3) .setTabListener(this)); actionBar.setSelectedNavigationItem(0); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // Restore the previously serialized current tab position. if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) { getActionBar().setSelectedNavigationItem( savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM)); } } @Override public void onSaveInstanceState(Bundle outState) { // Serialize the current tab position. outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar() .getSelectedNavigationIndex()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, show the tab contents in the // container view. //Fragment fragment = new DummySectionFragment(); //Bundle args = new Bundle(); //args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, // tab.getPosition() + 1); //fragment.setArguments(args); //getSupportFragmentManager().beginTransaction() // .replace(R.id.container, fragment).commit(); if (tab.getPosition() == 1) { Fragment fragment = new SectionFragmentOne(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1); fragment.setArguments(args); getSupportFragmentManager().beginTransaction() .replace(R.id.container, fragment).commit(); } else if (tab.getPosition() == 2) { Fragment fragment = new SectionFragmentTwo(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1); fragment.setArguments(args); getSupportFragmentManager().beginTransaction() .replace(R.id.container, fragment).commit(); } else { Fragment fragment = new SectionFragmentMain(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1); fragment.setArguments(args); getSupportFragmentManager().beginTransaction() .replace(R.id.container, fragment).commit(); } } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A dummy fragment representing a section of the app, but that simply * displays dummy text. */ public static class DummySectionFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ public static final String ARG_SECTION_NUMBER = "section_number"; public DummySectionFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Create a new TextView and set its text to the fragment's section // number argument value. TextView textView = new TextView(getActivity()); textView.setGravity(Gravity.CENTER); textView.setText(Integer.toString(getArguments().getInt( ARG_SECTION_NUMBER))); return textView; } } public class SectionFragmentMain extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ public static final String ARG_SECTION_NUMBER = "section_number"; public SectionFragmentMain() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //layout fragment yang digunakan bisa diset disini View rootView = inflater.inflate(R.layout.fragment_main, container, false); //komponen button dan lain-lain //dan event bisa diset disini btnone = (Button)rootView.findViewById(R.id.btnone); btnone.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub final ActionBar actionBar = getActionBar(); actionBar.setSelectedNavigationItem(1); } }); return rootView; // Create a new TextView and set its text to the fragment's section // number argument value. //TextView textView = new TextView(getActivity()); //textView.setGravity(Gravity.CENTER); //textView.setText(Integer.toString(getArguments().getInt( // ARG_SECTION_NUMBER))); //return textView; } } public class SectionFragmentOne extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ public static final String ARG_SECTION_NUMBER = "section_number"; public SectionFragmentOne() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_one, container, false); btntwo = (Button)rootView.findViewById(R.id.btntwo); btntwo.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub final ActionBar actionBar = getActionBar(); actionBar.setSelectedNavigationItem(2); } }); return rootView; // Create a new TextView and set its text to the fragment's section // number argument value. //TextView textView = new TextView(getActivity()); //textView.setGravity(Gravity.CENTER); //textView.setText(Integer.toString(getArguments().getInt( // ARG_SECTION_NUMBER))); //return textView; } } public class SectionFragmentTwo extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ public static final String ARG_SECTION_NUMBER = "section_number"; public SectionFragmentTwo() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_two, container, false); btnmain = (Button)rootView.findViewById(R.id.btnmain); btnmain.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub final ActionBar actionBar = getActionBar(); actionBar.setSelectedNavigationItem(0); } }); return rootView; // Create a new TextView and set its text to the fragment's section // number argument value. //TextView textView = new TextView(getActivity()); //textView.setGravity(Gravity.CENTER); //textView.setText(Integer.toString(getArguments().getInt( // ARG_SECTION_NUMBER))); //return textView; } } }

Untuk file konfigurasi AndroidManifest.xml tidak perlu ada perubahan seperti ini :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.amijaya.android_tabs_navigation"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.amijaya.android_tabs_navigation.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>

Setelah dijalankan hasilnya sebagai berikut, aplikasi mempunyai beberapa buah Tabs.


Pada aplikasi tersebut juga sudah diberi contoh bagaimana cara menambahkan button atau komponen lain pada masing-masing tampilan fragment dan bagaimana memberi event dan menambahkan codingnya.


Kode Program selengkapnya dapat didownload disini, jika kesulitan ini caranya mendownload.

Semoga berguna :)

Tidak ada komentar:

Posting Komentar