Search This Blog

Monday 25 June 2012

Using Fragments in Android

You can use the fragments to display the multiple user-interface panes in single screen. The fragments can be create by creating a subclass of the Fragment class.

You can use the standard class also to create your own fragments. The standard fragment classes are as follows

  • DialogFragment - displays the floating dialog window
  • ListFragment - display the list of items managed by the adapter
  • PreferencesFragment - displays a hierarchy of objects (settings)
The fragment class provide the similar methods like activity to implement its lifecycle. The methods which you must implement while designing the fragment are as follows

OnCreate() - The system calls this when the system is creating the fragment.

OnCreateView() - The system calls this when first time the fragment is drawing its user interface.

OnPause() - The system calls this when user is leaving the fragment and the fragment is moving to back-stack.

For Example the SampleFragment extending the Fragment class. The onCreateView method provides the UI for the fragment. 
public static class SampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.sample_fragment, container, false);
    }
}

The sample_fragment.xml is the layout file for the sample fragment.

Now you can use this fragment in your activity using the fragment transactions. To create or start a fragment transaction you need to get the FragmentManager of your activity while activity is running

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

Now you can add the fragment to the container of the ViewGroup.

SampleFragment fragment = new SampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

No comments:

Post a Comment