Saturday, February 2, 2013

Fragments and Its Usage

Fragments and Its Usage - Hallo sahabat Google Android Developer Tutorial, Pada Artikel yang anda baca kali ini dengan judul Fragments and Its Usage, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel Fragments and its Usage practical Tutorial, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : Fragments and Its Usage
link : Fragments and Its Usage

Baca juga


Fragments and Its Usage



FRAGMENTS



Fragments are more of a UI benefit  user sometimes to see two different views of two different classes on the same screen. If in your moment of creativity you decide it would be nice to display your application with a, say, a listView that takes up half the screen and a webView that takes up the other half - so that when you click on a list item in fragment A it passes an intent to the webView in fragment B, and suddenly you see what you just clicked w/o the app switching activities - then you could use a fragment. Bottom line: Fragments are two or more activities on the screen at the same time.

Figure 1. An example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.
The Android Support Library provides a JAR file with an API library that allows you to use some of the more recent Android APIs in your app while running on earlier versions of Android. For instance, the Support Library provides a version of theFragment APIs that you can use on Android 1.6 (API level 4) and higher
1.Create  Android project with details as listed in table below
Property name
Property value
Project name
SRM_FragmentTutorial
Package name
in.ac.srmuniv
Activity name
-unselect-
Layout xml name
-unselect-

2.Copy the code  to the file article_view.xml in res/layout folder 
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/article"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"

    android:textSize="18sp" />
3.Copy the code  to the file news_article.xml in res/layout folder 

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
4.Copy the code  to the file news_articles.xml in res/layout folder 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment android:name="in.ac.srmuniv.HeadlinesFragment"
              android:id="@+id/headlines_fragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

    <fragment android:name="in.ac.srmuniv.ArticleFragment"
              android:id="@+id/article_fragment"
              android:layout_weight="2"
              android:layout_width="0dp"
              android:layout_height="match_parent" />


</LinearLayout>
5.Copy the code in ArticleFragment.java. Fragment.
package in.ac.srmuniv.fragmentstutorial;

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

public class ArticleFragment extends Fragment {
    final static String ARG_POSITION = "position";
    int mCurrentPosition = -1;

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

        // If activity recreated (such as from screen rotate), restore
        // the previous article selection set by onSaveInstanceState().
        // This is primarily necessary when in the two-pane layout.
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }

        // Inflate the layout for this fragment
        returninflater.inflate(R.layout.article_view, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();

        // During startup, check if there are arguments passed to the fragment.
        // onStart is a good place to do this because the layout has already been
        // applied to the fragment at this point so we can safely call the method
        // below that sets the article text.
        Bundle args = getArguments();
        if (args != null) {
            // Set article based on argument passed in
            updateArticleView(args.getInt(ARG_POSITION));
        } else if (mCurrentPosition != -1) {
            // Set article based on saved instance state defined during onCreateView
            updateArticleView(mCurrentPosition);
        }
    }

    public void updateArticleView(int position) {
        TextView article = (TextView) getActivity().findViewById(R.id.article);
        article.setText(IPSum.Articles[position]);
        mCurrentPosition = position;
    }

    @Override
    public voidonSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // Save the current article selection in case we need to recreate the fragment
        outState.putInt(ARG_POSITION, mCurrentPosition);
    }

}

6.Copy the code in HeadLinesFragment.java. Fragment.
package in.ac.srmuniv.fragmentstutorial;

importandroid.app.Activity;
import android.os.Build;
import android.os.Bundle;
importandroid.support.v4.app.ListFragment;
import android.view.View;
importandroid.widget.ArrayAdapter;
importandroid.widget.ListView;

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interfaceOnHeadlineSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);
    }

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

        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, IPSum.Headlines));
    }

    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if(getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw newClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    @Override
    public voidonListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        mCallback.onArticleSelected(position);
       
        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
    }

}

8.Copy the code in IPsum.java 
package in.ac.srmuniv.fragmentstutorial;

public class IPSum {

    static String[] Headlines = {
        "About SRM",
        "SRM Vision"
    };

    static String[] Articles = {
        "Article One\n\nSRM University is one of the top ranking universities in India with 33,044 students and 2358 faculty across all the campus, offering a wide range of undergraduate, postgraduate and doctoral programs in Engineering, Management, Medicine and Health sciences, and Science and Humanities.",
        "Article Two\n\nTo emerge as a World - Class University in creating and disseminating knowledge, and providing students a unique learning experience in science, technology, medicine, management and other areas of scholarship that will best serve the world and betterment of mankind."
    };

9.Copy the code in MainActivity.java. Activity.
package in.ac.srmuniv.fragmentstutorial;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.os.Bundle;
importandroid.support.v4.app.FragmentActivity;
importandroid.support.v4.app.FragmentTransaction;
import android.util.Log;
importandroid.view.Display;
importandroid.view.WindowManager;

public class MainActivity extends FragmentActivity
        implements HeadlinesFragment.OnHeadlineSelectedListener {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager wm = getWindowManager();
        Display d = wm.getDefaultDisplay();
        if(d.getWidth()> 480) {
        //--For Tablet
         setContentView(R.layout.news_articles);
        }
        else{
        //---For Mobiles
         setContentView(R.layout.news_article);
        }
               // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if (findViewById(R.id.fragment_container) != null) {
           Log.d("Fragment","Dynamic");
            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            //; Create an instance of ExampleFragment
            HeadlinesFragment firstFragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)
 getSupportFragmentManager().findFragmentById(R.id.article_fragment);
        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...
          Log.d("Fragment","static");
            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);

        } else {
            // If the frag is not available, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }

}
10.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.fragmentstutorial"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.ac.srmuniv.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>
11,Run the application by right clicking the application select Run as->Run Configuration-Target device->select a tablet emulator (10.1 WVGA emulator should be created)



Figurre 2 Shows different emulators with varying emulators with different screen size configuration.

Figure 3 Shows the output in Tablet with MainActivity displaying both HeadLinesfragment  and ArticleFragment occupying  the view of the  layout. 

Figure 4 Shows on selecting a list item in HeadLinesFragment  which is a List Fragment  Article content is displayed in the ArticleFragment 
12.Now run the same application again with Target device being SRM_Mobile(a 320 x 480 emulator)


Figure 5 Shows SRM_Mobile emulator is selected to run the same application.
Figure 6  Shows the SRM_Mobile emulator which displays  Headlinesfragment dynamicaly addded to the FrameLayout .


Figure 7 Shows the SRM_Mobile emulator ArticleFragment dynamicaly addded  and replaces HeadlinesFragment fragment when  a list item in  selected from HeadlinesFragment

CODE EXPLANATION
WindowManager wm = getWindowManager();
        Display d = wm.getDefaultDisplay();
        if(d.getWidth() > 480) {
        //--For Tablet
         setContentView(R.layout.news_articles);
        }
        else{
        //---For Mobiles
         setContentView(R.layout.news_article);
        }
                            The application's MainActivity above code  checks size of the screen width and decides whether the device is bigger screen device or smaller screen device(Mobile or Tablet).It  loads news_articles.xml layout which has static fragments attached in to the Linear layout ( HeadLinesFragment  and ArticleFragment) if the emulator(or device)  is Tablet (with the width is less than 480dp just for our example).If the device is identified as Mobile (width will be greater than 480 dp) It loads  news_article.xml layout which has FrameLayout as the main container will be inflated to the view of the MainActivity which will be  container for dynamically created fragments.
                                                                 The code in onCreate() method of MainActivity 
           if (findViewById(R.id.fragment_container) != null) ensures that news_article.xml is inflated(which means Mobile device is in operation).So we have to dynamically add the first fragment(HeadLinesFragments) to the FrameLayout which is the container for the two fragments.Here the second Fragment ArticleFragment will replace the Headlines Fragment when an item in the List of HeadLines fragment is selected.
For tablet devices  news_articles.xml  will be the inflated view layout for MainActivity which has both Fragments statically created  through the layout manager and available in layout space of the activity. 
if (articleFrag != null) code in  public void onArticleSelected(int position) method ensures that news_articles.xml is inflated(which means Tablet device is in operation).Her we call updateArticleView(int position) method in ArticleFragment to update the content based on the list selection in HeadLinesFragment.


Demikianlah Artikel Fragments and Its Usage

Sekianlah artikel Fragments and Its Usage kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

Anda sekarang membaca artikel Fragments and Its Usage dengan alamat link https://googleandroiddevelopertutorial.blogspot.com/2013/02/fragments-and-its-usage.html

Artikel Terkait

Fragments and Its Usage
4/ 5
Oleh

Berlangganan

Suka dengan artikel di atas? Silakan berlangganan gratis via email