Android Navigation Drawer,Fragments Tutorial | the latest tutorial is now and around Android

Android Navigation Drawer,Fragments Tutorial

Android Navigation Drawer,Fragments Tutorial - Hallo sahabat the latest tutorial is now and around Android, Pada Artikel yang anda baca kali ini dengan judul Android Navigation Drawer,Fragments Tutorial, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel Android navigation Drawer and Fragments usage, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : Android Navigation Drawer,Fragments Tutorial
link : Android Navigation Drawer,Fragments Tutorial

Baca juga


Android Navigation Drawer,Fragments Tutorial

Android Navigation Drawer,Fragments  Tutorial
Navigation Drawer
Navigation Drawer is a recent popular Android UI design for many Apps like Facebook , Google plus , ,you tube, amazon kindle gmail etc.The navigation drawer (Sliding Menu ) is a list “ListView” of options on the left edge of the screen.is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar.
For example, the following layout uses a DrawerLayout with two child views: a FrameLayout to contain the main content (populated by a Fragment at runtime), and a ListView for the navigation drawer.
Fragment
A  Fragment represents a behavior or a portion of user interface in an Activity.A Fragment must always be embedded in an activity and you can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
Fragments LifeCycle
Figure1 Shows Fragment Life cycle.
              A  fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them.
Dynamic Fragments
There are two ways you can add a fragment to the activity layout:
  1. Declare the fragment inside the activity's layout file.(Static Fragments)
  2.  Programmatically add the fragment to an existing ViewGroup.
                   To make fragment transactions in your activity (such as add, remove, or replace a fragment), you must use APIs from FragmentTransaction. You can get an instance of FragmentTransaction from your Activity like this:
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                     You can then add a fragment using the add() method, specifying the fragment to add and the view in which to insert it. For example:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
                                  The first argument passed to add() is the ViewGroup in which the fragment should be placed, specified by resource ID, and the second parameter is the fragment to add.
Once you've made your changes with FragmentTransaction, you must call commit() for the changes to take effect.
The Demonstrative project uses Sliding menu (Navigation Drawer) to select Fragments to send messages through SMS or EMail.A common Message Fragment passes typed message available for both SMS and EMail fragment .Demonstrates Fragment communication and Dynamic replacement of Fragments.
1.Create  Android project with details as listed in the table below.
Property name
Property value
Project name
SRM_NavigationDrawerTutorial
Package name
in.ac.srmuniv.navigationdrawertutorial
Activity name
MainActivity
Layout xml name
activity_main

2.Copy the code in SubjectMessage.java. interface.
packagein.ac.srmuniv.navigationdrawertutorial.javacomponents;

public interface SubjectMessage {
     void setMessage(String msg, int frag);
     String getMessage();
}
3.Copy the code  to the file activity_main.xml in res/layout folder.
<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" >

    <!-- The main content view -->

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

    <!-- The navigation drawer list -->

    <ListView
        android:id="@+id/slider_list"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#ffffff"
        android:choiceMode="singleChoice"
        android:divider="@android:color/black"
        android:dividerHeight="0dp" />


</android.support.v4.widget.DrawerLayout
4.Copy the code  to the file strings.xml in res/values folder 
<?xml version="1.0"encoding="utf-8"?>
<resources>

    <string name="app_name">SRM_NavigationDrawerTutorial</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="imgdesc">imgdesc</string>

    <string-array name="titles">
        <item>Message</item>
        <item>SMS</item>
        <item>E-Mail</item>
    </string-array>

    <array name="icons">
        <item>@drawable/message</item>
        <item>@drawable/sms</item>
        <item>@drawable/email</item>
    </array>

</resources>
5.Copy the code in MainActivity.java. Activity.
packagein.ac.srmuniv.navigationdrawertutorial.androidcomponents;

importin.ac.srmuniv.navigationdrawertutorial.androidcomponents.R;
importin.ac.srmuniv.navigationdrawertutorial.javacomponents.RowItem;
importin.ac.srmuniv.navigationdrawertutorial.javacomponents.SubjectMessage;

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

importandroid.annotation.SuppressLint;
importandroid.annotation.TargetApi;
importandroid.app.Fragment;
importandroid.app.FragmentManager;
importandroid.content.res.Configuration;
importandroid.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
importandroid.support.v4.app.ActionBarDrawerToggle;
importandroid.support.v4.app.FragmentActivity;
importandroid.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
importandroid.view.MenuItem;
import android.view.View;
importandroid.widget.AdapterView;

import android.widget.ListView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends FragmentActivity implements SubjectMessage {

     String[] menutitles;
     TypedArray menuIcons;

     // navdrawer title
     private CharSequence mDrawerTitle;
     private CharSequence mTitle;

     private DrawerLayout mDrawerLayout;
     private ListView mDrawerList;
     privateActionBarDrawerToggle mDrawerToggle;

     private List<RowItem> rowItems;
     private CustomAdapter adapter;
     private String commMsg = "";

     @SuppressLint("NewApi")
     @Override
     protected void onCreate(Bundle savedInstanceState) {
           // TODO Auto-generated method stub
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);

           mTitle = mDrawerTitle = getTitle();

           menutitles = getResources().getStringArray(R.array.titles);
           menuIcons = getResources().obtainTypedArray(R.array.icons);

           mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
           mDrawerList = (ListView) findViewById(R.id.slider_list);

           rowItems = newArrayList<RowItem>();

           for (int i = 0; i < menutitles.length; i++) {
                RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
                           i, -1));
                rowItems.add(items);
           }
           menuIcons.recycle();
           adapter = newCustomAdapter(getApplicationContext(), rowItems);
           mDrawerList.setAdapter(adapter);
           mDrawerList.setOnItemClickListener(newSlideitemListener());

           // enabling action bar app icon and behaving it as toggle button
           getActionBar().setDisplayHomeAsUpEnabled(true);
           getActionBar().setHomeButtonEnabled(true);

           mDrawerToggle = newActionBarDrawerToggle(this, mDrawerLayout,
                     R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
                public void onDrawerClosed(View view) {
                     getActionBar().setTitle(mTitle);
                     // calling onPrepareOptionsMenu() to show action bar icons
                     invalidateOptionsMenu();
                }

                public void onDrawerOpened(View drawerView) {
                     getActionBar().setTitle(mDrawerTitle);
                     // calling onPrepareOptionsMenu() to hide action bar icons
                     invalidateOptionsMenu();
                }
           };

           mDrawerLayout.setDrawerListener(mDrawerToggle);

           if (savedInstanceState == null) {
                // on first time display view for first nav item
                updateDisplay(0);
           }
     }

     class SlideitemListener implementsListView.OnItemClickListener {
           @Override
           public voidonItemClick(AdapterView<?> parent, View view, int position,
                     long id) {
                updateDisplay(position);
           }

     }

     @TargetApi(Build.VERSION_CODES.HONEYCOMB)
     private void updateDisplay(int position) {
           Fragment fragment = null;
           switch (position) {
           case 0:
                fragment = new Message_Fragment();
                break;
           case 1:
                fragment = new SMS_Fragment();
                break;
           case 2:
                fragment = new EMail_Fragment();
                break;
           default:
                break;
           }

           if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                           .replace(R.id.frame_container, fragment).commit();
                // update selected item and title, then close the drawer
                setTitle(menutitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);
           } else {
                // error in creating fragment
                Log.e("MainActivity", "Error in creating fragment");
           }

     }

     @Override
     public voidsetTitle(CharSequence title) {
           mTitle = title;
           getActionBar().setTitle(mTitle);
     }

     @Override
     public booleanonCreateOptionsMenu(Menu menu) {
           getMenuInflater().inflate(R.menu.main, menu);
           return true;
     }

     @Override
     public booleanonOptionsItemSelected(MenuItem item) {
           // toggle navdrawer on selecting action bar app icon/title
           if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
           }
           // Handle action bar actions click
           switch (item.getItemId()) {
           case R.id.action_settings:
                return true;
           default:
                return super.onOptionsItemSelected(item);
           }
     }

     /***
      * Called when invalidateOptionsMenu() is triggered
      */
     @Override
     public booleanonPrepareOptionsMenu(Menu menu) {
           // if navdrawer is opened, hide the action items
           boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
           menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
           return super.onPrepareOptionsMenu(menu);
     }

     /**
      * When using the ActionBarDrawerToggle, you must call it during
      * onPostCreate() and onConfigurationChanged()...
      */

     @Override
     protected void onPostCreate(Bundle savedInstanceState) {
           super.onPostCreate(savedInstanceState);
           // Sync the toggle state after onRestoreInstanceState has occurred.
           mDrawerToggle.syncState();
     }

     @Override
     public voidonConfigurationChanged(Configuration newConfig) {
           super.onConfigurationChanged(newConfig);
           // Pass any configuration change to the drawer toggles
           mDrawerToggle.onConfigurationChanged(newConfig);
     }

     @Override
     public void setMessage(String str, int frag) {
           commMsg = str;
           Log.d("MainActivity", commMsg);
           Log.d("MainActivity", Integer.valueOf(frag).toString());
           switch (frag) {
           case 1:
                SMS_Fragment sms = (SMS_Fragment) getFragmentManager()
                           .findFragmentById(R.id.sms_fragmentlay);
                if (sms == null) {
                     System.out.println("Dual fragment - 1");
                     sms = new SMS_Fragment();
                     sms.getSMSMessage(commMsg);
                     // We are in dual fragment (Tablet and so on)
                     FragmentManager fm = getFragmentManager();
                     android.app.FragmentTransaction ft = fm.beginTransaction();
                     ft.replace(R.id.frame_container, sms);
                     ft.commit();
                }

                else {
                     Log.d("SwA", "Dual Fragment update");
                     // sms.getEMailSubject(commMsg);
                }
                break;
           case 2:
                EMail_Fragment email = (EMail_Fragment) getFragmentManager()
                           .findFragmentById(R.id.email_fragmentlay);
                if (email == null) {
                     System.out.println("Dual fragment - 1");
                     email = new EMail_Fragment();
                     email.getEMailMessage(commMsg);
                     // We are in dual fragment (Tablet and so on)
                     FragmentManager fm = getFragmentManager();
                     android.app.FragmentTransaction ft = fm.beginTransaction();
                     ft.replace(R.id.frame_container, email);
                     ft.commit();
                }

                else {
                     Log.d("SwA", "Dual Fragment update");
                     // sms.getEMailSubject(commMsg);
                }
           }

     }

     public String getMessage() {
           Log.d("MainActivity", commMsg);
           return commMsg;
     }
}
6.Copy the code  to the file drawerlist_item.xml in res/layout folder
 <?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:padding="5dp" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:contentDescription="@string/imgdesc" />
         
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@id/icon"
        android:gravity="center_vertical"
        android:textColor="#000000"
        android:textSize="20sp" />

</RelativeLayout>
7.Copy the code in CustomAdapter.java.
packagein.ac.srmuniv.navigationdrawertutorial.androidcomponents;

import in.ac.srmuniv.navigationdrawertutorial.androidcomponents.R;
importin.ac.srmuniv.navigationdrawertutorial.javacomponents.RowItem;
  
import java.util.List;

importandroid.app.Activity;
importandroid.content.Context;
importandroid.view.LayoutInflater;
import android.view.View;
importandroid.view.ViewGroup;
importandroid.widget.BaseAdapter;
importandroid.widget.ImageView;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter {

     Context context;
     List<RowItem> rowItem;

     CustomAdapter(Context context, List<RowItem> rowItem) {
           this.context = context;
           this.rowItem = rowItem;
     }

     @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.drawerlist_item, null);
           }

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

           RowItem row_pos = rowItem.get(position);
           // setting the image resource and title
           imgIcon.setImageResource(row_pos.getIcon());
           txtTitle.setText(row_pos.getTitle());

           return convertView;
     }

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

     @Override
     public Object getItem(int position) {
           return rowItem.get(position);
     }

     @Override
     public long getItemId(int position) {
           return rowItem.indexOf(getItem(position));
     }

}
8.Copy the code in RowItem.java.
packagein.ac.srmuniv.navigationdrawertutorial.javacomponents;

public class RowItem {

     private String title;
     private int icon;

     public RowItem(String title, int icon) {
           this.title = title;
           this.icon = icon;

     }

     public String getTitle() {
           return title;
     }

     public void setTitle(String title) {
           this.title = title;
     }

     public int getIcon() {
           return icon;
     }

     public void setIcon(int icon) {
           this.icon = icon;
     }

}
9.Copy the code  to the file message.xml in res/layout folder.For Message_Fragment 
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/message_fragmentlay"
    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:layout_gravity="center_horizontal"
        android:text="MESSAGE"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.05"
        android:ems="10"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/smsbutton"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="SMS" />

        <Button
            android:id="@+id/emailbutton"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="E-Mail" />
    </LinearLayout>


</LinearLayout>
10.Copy the code in Message_Fragment.java. Fragment.
packagein.ac.srmuniv.navigationdrawertutorial.androidcomponents;

import in.ac.srmuniv.navigationdrawertutorial.androidcomponents.R;
importin.ac.srmuniv.navigationdrawertutorial.javacomponents.SubjectMessage;
importandroid.annotation.SuppressLint;
importandroid.app.Activity;
importandroid.app.Fragment;
import android.os.Bundle;
importandroid.view.LayoutInflater;
import android.view.View;
importandroid.view.ViewGroup;
importandroid.widget.Button;
importandroid.widget.EditText;

importandroid.view.View.OnClickListener;
@SuppressLint("NewApi")
public class Message_Fragment extends Fragment {
     Button smsButton;
     Button emailButton;
     EditText messageEditText;

     SubjectMessage messageInterface;

     @Override
     public void onAttach(Activity activity) {
           // We verify that our activity implements the listener
           if (!(activity instanceof SubjectMessage))
                throw newClassCastException();
           else
                messageInterface = (SubjectMessage) getActivity();
           super.onAttach(activity);
     }

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
           View rootView = inflater.inflate(R.layout.message_fragment, container,
                     false);
           smsButton = (Button) rootView.findViewById(R.id.smsbutton);
           emailButton = (Button) rootView.findViewById(R.id.emailbutton);
           messageEditText = (EditText) rootView.findViewById(R.id.message);
           return rootView;
     }

     @Override
     public voidonActivityCreated(Bundle savedInstanceState) {
           smsButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                     messageInterface.setMessage(messageEditText.getText()
                                .toString(), 1);

                }
           });
           emailButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                     messageInterface.setMessage(messageEditText.getText()
                                .toString(), 2);

                }
           });
           super.onActivityCreated(savedInstanceState);
     }

}
11.Copy the code  to the file sms_fragment.xml in res/layout folder.For SMS_Fragment 

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

    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Phone Number : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:phoneNumber="true" >
    </EditText>

    <TextView
        android:id="@+id/textViewSMS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter SMS Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:inputType="textMultiLine"
        android:lines="5" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center" >

        <Button
            android:id="@+id/sendsmsbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Send" />

        <Button
            android:id="@+id/clearsms"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Clear"/>
    </LinearLayout>

</LinearLayout>
12.Copy the code in SMS_Fragment.java. Fragment.
packagein.ac.srmuniv.navigationdrawertutorial.androidcomponents;

import in.ac.srmuniv.navigationdrawertutorial.androidcomponents.R;
importin.ac.srmuniv.navigationdrawertutorial.javacomponents.SubjectMessage;
importandroid.annotation.SuppressLint;
importandroid.app.Activity;
importandroid.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
importandroid.view.LayoutInflater;
import android.view.View;
importandroid.view.ViewGroup;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;
importandroid.view.View.OnClickListener;



@SuppressLint("NewApi")
public class SMS_Fragment extends Fragment {
     Button sendButton;
     Button clearButton;
     EditText textPhoneNo;
     EditText textSMS;

     String message = null;

     @Override
     public void onAttach(Activity activity) {
           if (!(activity instanceof SubjectMessage))
                throw newClassCastException();
           message = ((SubjectMessage) getActivity()).getMessage();
           super.onAttach(activity);
     }

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
           View rootView = inflater.inflate(R.layout.sms_fragment, container,
                     false);
           sendButton = (Button) rootView.findViewById(R.id.sendsmsbutton);
           clearButton = (Button) rootView.findViewById(R.id.clearsms);
           textPhoneNo = (EditText) rootView.findViewById(R.id.editTextPhoneNo);
           textSMS = (EditText) rootView.findViewById(R.id.editTextSMS);

           return rootView;
     }

     @Override
     public voidonActivityCreated(Bundle savedInstanceState) {
           textSMS.setText(message);
           sendButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                     Intent smsVIntent = new Intent(Intent.ACTION_VIEW);
                     // prompts only sms-mmsclients

                     smsVIntent.setType("vnd.android-dir/mms-sms");
                     // extra fields for number and message respectively
                     smsVIntent
                                .putExtra("address", textPhoneNo.getText().toString());
                     smsVIntent.putExtra("sms_body", textSMS.getText().toString());
                     try {
                           startActivity(smsVIntent);
                     } catch (Exception ex) {
                           Toast.makeText(getActivity().getApplicationContext(),
                                     "Your sms has failed...", Toast.LENGTH_LONG).show();
                           ex.printStackTrace();
                     }
                }
           });
           clearButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                     textSMS.setText("");

                }
           });
           super.onActivityCreated(savedInstanceState);
     }

     void getSMSMessage(String str) {
           message = str;
     }
 }
13.Copy the code  to the file email_fragment.xml in res/layout folder.For EMail_Fragment 

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

    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="To : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress" >

        <requestFocus />

    </EditText>

    <TextView
        android:id="@+id/textViewSubject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subject : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextSubject"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         >
    </EditText>

    <TextView
        android:id="@+id/textViewMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextMessage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:inputType="textMultiLine"
        android:lines="5" />
     <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        >

        <Button
            android:id="@+id/sendemailButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send"
            android:layout_weight="1" />

        <Button
            android:id="@+id/clearmsg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Clear"
            android:layout_weight="1"  />
    </LinearLayout>

</LinearLayout>
14.Copy the code in EMail_Fragment.java. Fragment.

packagein.ac.srmuniv.navigationdrawertutorial.androidcomponents;

import in.ac.srmuniv.navigationdrawertutorial.androidcomponents.R;
import in.ac.srmuniv.navigationdrawertutorial.javacomponents.SubjectMessage;
importandroid.annotation.SuppressLint;
importandroid.app.Activity;
importandroid.app.Fragment;
importandroid.content.Intent;
import android.os.Bundle;
importandroid.view.LayoutInflater;
import android.view.View;
importandroid.view.ViewGroup;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.view.View.OnClickListener;

@SuppressLint("NewApi")
public class EMail_Fragment extends Fragment {

     Button sendButton;
     Button clearButton;
     EditText textTo;
     EditText textSubject;
     EditText textMessage;
     String subject = null;

     @Override
     public void onAttach(Activity activity) {
           if (!(activity instanceof SubjectMessage))
                throw newClassCastException();
           subject = ((SubjectMessage) getActivity()).getMessage();
           super.onAttach(activity);
     }

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
           View rootView = inflater.inflate(R.layout.email_fragment, container,
                     false);
           sendButton = (Button) rootView.findViewById(R.id.sendemailButton);
           clearButton = (Button) rootView.findViewById(R.id.clearmsg);
           textTo = (EditText) rootView.findViewById(R.id.editTextTo);
           textSubject = (EditText) rootView.findViewById(R.id.editTextSubject);
           textMessage = (EditText) rootView.findViewById(R.id.editTextMessage);

           return rootView;
     }
     @Override
     public void onActivityCreated(Bundle savedInstanceState) {
           textMessage.setText(subject);
           sendButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                     String to = textTo.getText().toString();
                     String subject = textSubject.getText().toString();
                     String message = textMessage.getText().toString();

                     Intent email = new Intent(Intent.ACTION_SEND);
               email.putExtra(Intent.EXTRA_EMAILnew String[] { to });
                     // email.putExtra(Intent.EXTRA_CC, new String[]{ to});
                     // email.putExtra(Intent.EXTRA_BCC, new String[]{to});
                     email.putExtra(Intent.EXTRA_SUBJECT, subject);
                     email.putExtra(Intent.EXTRA_TEXT, message);

                     // need this to prompts email client only
                     email.setType("message/rfc822");
                     startActivity(Intent.createChooser(email,
                                "Choose an Email client :"));

                }
           });
           clearButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                     textMessage.setText("");

                }
           });
           super.onActivityCreated(savedInstanceState);
     }

     voidgetEMailMessage(String str) {
           subject = str;
     }

}
15.Copy the code  to the file menu.xml in res/menu folder.

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

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>

</menu>
16.No need to modify Androidmanifest.xml
<?xml version="1.0"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.ac.srmuniv.navigationdrawertutorial.androidcomponents"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.ac.srmuniv.navigationdrawertutorial.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>
16.Run the application in the emulator.
             
Figure 2 Shows Message_Fragment in view when    App is loaded Figure 3 Shows when user swipe or tap the Action bar icon Navigation Drawer is available
                 
 
Figure 4 Shows message being typed in Message_Fragment.Figure 5 Shows when SMS button being clicked in Message_Fragment replaces it with SMS_Fragment Dynamically with message passed to it through the parent Activity.

                Figure 6 Shows Message Application called through Intent when  send button is clicked.Figure 7 Shows Message_Fragment replaced dynamically by EMail_Fragment with message passed along through parent Activity.

 

Figure 8 Shows EMail Application being called through Intent when send button clicked Figure 9 Shows project anatomy.
CODE EXPLANATION 
                                     In our project  DrawerLayout is  the main container layout in  activity_main.xml is the inflated view  for the MainActivity.Add two views, one for the main view “when the drawer is hidden” and one for the drawer.We are dynamically going to insert Fragments.The main content view (FrameLayout)  must be the first child in the DrawerLayout because the XML order implies z-ordering and the drawer must be on top of the content.
  1.  The list item layout is a imageview and  TextView(for Message,SMS,Email), but we can do styling such as padding, background color, text color and text size.res/layout/drawerlist_item_item.xml.
  2. We need to define string array for the drawer list.Get the list “array” of items to be added to the drawer list from res/values/strings.xml         mDrawerList.setAdapter(adapter);                    mDrawerList.setOnItemClickListener(new SlideitemListener());
  3. Get the reference to the ListView Call ListView.setAdapter(ArrayAdapter).
 class SlideitemListener implements ListView.OnItemClickListener {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position,
                     long id) {
                updateDisplay(position);
           }

     }
     4.The inner class called SlideitemListener , Inside the MainActivity class which override onItemClick method inside this method call updateDisplay() method by passing position as a parameter to it and then inside updateDisplay by knowing  the position clicked ,we are replacing the current fragment with the respective fragment associated with the items of listview .you can find the updateDisplay method inside them MainActivity class .
                FragmentManager fragmentManager = getFragmentManager();
           fragmentManager.beginTransaction()                   .replace(R.id.frame_container, fragment).commit();
5.Dynamic replacement of one fragment with other is shown with above code in updateDisplay() method.Remember you are replacing the the containerID not the fragment ID.the fragment object is the selected list item from Sliding Menu.
Action Bar Open & Close the Drawer With App Icon
Get reference to DrawerLayout define in activity_main.xml.Declare ActionBarDrawerToggle
// enabling action bar appicon and behaving it as toggle button
           getActionBar().setDisplayHomeAsUpEnabled(true);
           getActionBar().setHomeButtonEnabled(true);

           mDrawerToggle = newActionBarDrawerToggle(this, mDrawerLayout,
                     R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
                public void onDrawerClosed(View view) {
                     getActionBar().setTitle(mTitle);
                     // calling onPrepareOptionsMenu() to show action bar icons
                     invalidateOptionsMenu();
                }

                public void onDrawerOpened(View drawerView) {
                     getActionBar().setTitle(mDrawerTitle);
                     // calling onPrepareOptionsMenu() to hide action bar icons
                     invalidateOptionsMenu();
                }
           };

           mDrawerLayout.setDrawerListener(mDrawerToggle);
The Listener enables to change Action Bar title,icon etc.it also invalidates option menu 
Fragments Life Cycle
onAttach():
EMail_Fragment code snippets 
@Override
     public void onAttach(Activity activity) {
           if (!(activity instanceof SubjectMessage))
                throw new ClassCastException();
           subject = ((SubjectMessage) getActivity()).getMessage();
           super.onAttach(activity);
     }
This signifies that the Activity has attached fragment on it and it doesn’t mean that all the views of Activity are created not it means that Activity is fully functional. This is just a point where you can reference the activity.In our app we test the instance of the parent Activity which holds it.Since the fragments could be reused by many activities in an App.We need to get the instance of the activity to do ant message passing.
onCreate():
Just a point which shows that Fragment is in the process of creation and in this method just try to access those values that you have saved on onSavedInstanceState(Bundle outState)
@Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
           View rootView = inflater.inflate(R.layout.message_fragment, container,
                     false);
           smsButton = (Button) rootView.findViewById(R.id.smsbutton);
           emailButton = (Button) rootView.findViewById(R.id.emailbutton);
           messageEditText = (EditText) rootView.findViewById(R.id.message);
           return rootView;
     }
onCreateView():
Here we inflate the layout or simply create the view and further if you have to do anything that takes reference to Activity don’t do it like creating dialogs,accessing views of Activity etc because,this place doesn’t ensure that hosting Activity is fully functional.Buttons and editText of the message fragments are instantiated.you need to get the rootView to use findViewById(). 
onActivityCreated():
EMail_Fragment code snippets
 textMessage.setText(subject);
           sendButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                              // Event handling code                                     
                                            } 
This place signifies that our hosting Activity views are created and hosting Activity is functional and this is the right place to do all your Activity related task.Setting the message value passed from Message_Fragment in editText..Event handling code implementation for send button calls in build EMail application for sending Tmail.
onResume():
Here code to do all the actions of the fragment is written 
Fragment communication
In our example we have three fragments ,Message_Fragment is a common entry form in which message typed can be passed , when user clicks the Button (SMS or Email) in the fragment 1 (Message_Fragment) the other one (SMS_Fragment (or) EMail_Fragment) is called.So we need to find a way to let these fragments to exchange data.
                    A fragment is a piece of code that can be re-used inside other activity so we don’t want to bind our fragment to a specific activity to not invalidate our work. In Java if we want to decouple two classes we can use an interface. So this interface solution fits perfectly. On the other hand we don’t want that our fragment exchange information directly because each fragment can rely only on the activity that holds it. So the simplest solution is that the activity implements an interface.
public interface SubjectMessage {
     void setMessage(String msg, int frag);
     String getMessage();
}
Message_Fragment.java
code snippets 
SubjectMessage messageInterface;
......
onAttach() method
 messageInterface = (SubjectMessage) getActivity();
......
onClick() method (SMS button)
messageInterface.setMessage(messageEditText.getText()
                                .toString(), 1);
.....
onClick() method (EMail button)
messageInterface.setMessage(messageEditText.getText()
                                .toString(), 2);
SMS/Email Fragment code snippets
subject = ((SubjectMessage) getActivity()).getMessage();
The Figure shows that message Fragment tests the instance of the parent activity holding the fragment and calls the method of the activity implemented by interface SubjectMessage.


Demikianlah Artikel Android Navigation Drawer,Fragments Tutorial

Sekianlah artikel Android Navigation Drawer,Fragments Tutorial kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

Anda sekarang membaca artikel Android Navigation Drawer,Fragments Tutorial dengan alamat link https://kokonghod.blogspot.com/2014/05/android-navigation-drawerfragments.html

0 Response to "Android Navigation Drawer,Fragments Tutorial"