Monday, 26 November 2012

Fragments


Fragments
A Fragments represents a behavior or a portion of user interface in an Avtivity.You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

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. When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.

1.)  Create a new project by File-> New -> Android Project name it FragmentExample.
2.)  Write following into main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">
 <FrameLayout
            android:id="@+id/simple_fragment"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1">
    </FrameLayout>
  <Button android:id="@+id/new_fragment"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="New fragment">
        <requestFocus />
    </Button>
 </LinearLayout>

3.)  Create and write following into fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="FragmentExample"/>

4.)  Create animator folder and write fragment left,right, entry and exit animation.
5.)  Run for output.

No comments:

Post a Comment