Saturday, April 28, 2012

Fragment in Android


A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
See more about Fragment at below link.
http://developer.android.com/guide/topics/fundamentals/fragments.html
For example, a news application can use one fragment to show a list of articles on the left and another fragment to display an article on the right—both fragments appear in one activity. A fragment should be a modular and reusable component in your application. The same concept is applied here.
There are few steps to create an example using Fragment. They are as follows.
Step - 1:
Define string arrays in /res/values/arrays.xml file.
- android_platforms : Contains all the Android Platforms (Left pane as List)
- platform_revisions : Contains all the contents for Android Platforms (Right pane as Content)
Step - 2:
- Create a class FragmentListContent.java which extends to Fragment. The FragmentListContent.java is used to fill out the content(name="platform_revisions") from arrays.xml of selected item from the list in fragment area.
- Add onCreateView(...) @Override method in FragmentListContent.java.
- Here, we are not inflating any other layout, so it would be return null.
        if (container == null) {
            return null;
        }
- Allow scroll for displaying content.
        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());
        int padding = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources()
                        .getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        scroller.addView(text);
- Get the content of the selected position from /res/values/arrays.xml.
        String[] REVISION = getResources().getStringArray(R.array.platform_revisions);
        text.setText(REVISION[getArguments().getInt("position", 0)]);
Step - 3:
- Create a class FragmentListTitles.java which extends to ListFragment. http://developer.android.com/reference/android/app/ListFragment.html.
- The FragmentListTitles.java is used to fill out Android Platforms(name="android_platforms") from arrays.xml into list. Already filled area would be replaced to existing content.
- Populate list
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getActivity(), android.R.layout.simple_list_item_activated_1);
        adapter.addAll(getResources().getStringArray(R.array.android_platforms));
        setListAdapter(adapter);
- Store state of current position
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /*** STORE STATE OF CURRENT POSITION ***/
        outState.putInt("current_position", mCurrentCheckedPosition);
        outState.putInt("shown_position", mCheckedPosition);
    }
- Create a method showDetails(int index) and add below code to update the existing content by replacing new content for selected item
        /*** UPDATE THE CONTENT FOR SELECTED ITEM FROM THE LIST ***/
        getListView().setItemChecked(index, true);

        if (mCheckedPosition != mCurrentCheckedPosition) {
            FragmentListContent listContent = FragmentListContent
                    .newInstance(index);

            /*** REPLACE THE TRANSACTION WITH EXISTING AND UPDATE CONTENT ***/
            FragmentTransaction transaction = getFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.fragment2, listContent);
            transaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.commit();
            mCurrentCheckedPosition = index;
        }
Step - 4:
- Create main_fragment.xml in /res/layout.
- Register FragmentListTitles in <fragment /> tag.
    <fragment
        android:id = "@+id/fragment1"
        android:name = "com.indianic.fragmentdemo.FragmentListTitles"
        android:layout_width = "0dp"
        android:layout_height = "match_parent"
        android:layout_weight = "1"
        android:layout_marginRight = "4dp">
    </fragment>
The android:name attribute has below format <package name>.<class name>
android:name = "com.indianic.fragmentdemo.FragmentListTitles"
- Set a FrameLayout to display content.
    <FrameLayout
         android:id = "@+id/fragment2"
         android:layout_weight = "1"
         android:layout_width = "0px"
         android:layout_height = "match_parent"
         android:background = "?android:attr/detailsElementBackground">
    </FrameLayout>
Step - 5:
- Run application.
Find the attached zip file for complete source code.
I would be glad to receive your suggestions regarding it.
Thanks.

No comments:

Post a Comment