Home > DeveloperSection > Beginner > Building a Dynamic UI with Fragments in Android

Building a Dynamic UI with Fragments in Android


Android Android  Android Activity  Android Layout  Gui 
Ratings:
0 Comment(s)
 1396  View(s)
Rate this:

Building a Dynamic UI with Fragments



Previously we discuss about Android Life cycle and its methods in following posts:


Now in this post, we are going to discuss a very interesting component called "Fragments"


To create a dynamic and multi-pane user interface on Android, we need to encapsulate UI components and activity behavior into modules that we can swap into and out of our activity. We can create this modules with the fragment class, which behave like a nested activity that can define its own layout and manage its own lifecycle

Having its own layout, a fragments can be configured in different combinations with the other fragments inside an activity to modify layout configurations for different screen sizes. For example, a small screen might show one fragment at a time, but a large screen can show one fragment at a time, but a large screen can show two or more.

 

Create a Fragment:

A fragment is like a sub-activity which we can reuse in different activities. We can achieve this by extending the Fragment class

 

Create a Fragment Class:

To create a fragment, first we need to create sub-class of the main fragment class. The sub-class need to include callback methods including onCreate(), onStart() , onPause() and onStop(). And the application must implement at least these three methods for every fragment:

·         onCreate()

·         onCreateView()

·         onPause()

 

 

//Import declarations

 

public static class MyFragment extends Fragment {

 

 @Overrride

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

      {

 

          return inflater. Inflater(R.layout.my_fragment,container, false);

 

       }

}

 

Add a fragment to an Activity

 

After having creating the fragment class, we need to add the same fragment to an activity. For this we have two simple approaches:

 

·         Add the fragment view in the Layout XML

·         Add the fragment at runtime, using FragmentManager and FragmentTransaction class

 

Add the Activity to an activity using XML

We can specify the fragment in the activity’s default layout .Her we simply need to insert the following code into the activity layout file

 

<fragment android: name=”com.example.myApp.MyFragment “

                     android: id=”@+id/my_fragment”

                     android:layout_width=”match_parent”

                    android:layout_height=”match_parent” />

 

 

Add a method to an activity at the run time:

 

We can add fragment to Activity during runtime. Also, if we intend to remove or replace any fragment while the Activity is running, the same must be done programmatically

As per this approach we need two classes: FragmentManger and FragmentTranscation for adding the fragment programmatically. Following snippet is the code that will be involved in the process:

 

Fragmentmanger manager = getSupportFragmentManager();

TransactionManager transaction = manager.beginTransaction();

Transaction.add(R.layout.my_fragment, my_Fragment);

Transaction.commit();

 

 

In the above code:

 The method add accepts two parameters as explained below:

1.      R.layout.my_fragment:  This is the unique ID that refers to the fragment layout

2.      myFragment: This is the Fragment object that needs to be added to the Activity

 

 

 

 

 

 

Replace one Fragment with Another

 

The procedure to replace a fragment is similar to adding one, but requires the replace () method instead of add (). Also, when we replace or remove one, it’s good to allow the user to navigate backwards and undo the changes. For this, we need to call addToBackStack() before we commit the FragmentTransaction. For Example,

 

//create fragment and give it an argument specifying the article it should show

MyFragment   newFragment = newMyFragment();

Bundle args = new Bundle();

args.putInt(MyFragment.ARG_POSITION, postion);

newFragment.setArguments(args);

 

FragmentTranscation transcation = getSupportFrameManager(). beginTransaction();

 

// Replace whatever is in the fragment_container view with this fragment,

// 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();

 

 

 

 

 

Communicating with other Fragments

IF we are inclined on reusing the Fragment UI components, we‘ll need to build each fragment as self-contained, modular components. After having defined these reusable fragments, you can choose to associate each one of them with an activity, followed by connecting them with the application logic for a complete realization of the flexible UI. Here’s the 3-step process of communicating with other fragments:

 

 

 

Step 1: Defining an interface

Here we need to decline an interface in the main Fragment class and implement the same within the activity. The fragment will then capture the interface implementation during the execution of onAttach() method. Thus, the fragment will call the interface methods for communicating with the Activity

 

 

 

Public MyFragment extends ListFragment{

      OnHeadLineSelecteedListener mCallback;

 

     // Container Activity must implement this interface

       public interface OnHeadlineSelectedListener {

          public void onArticleSelected(int position);

     }

@Override

public void oAttach(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 new ClassCastException(activity.toString()

                                        + “ must implement onHedlineSelectedListener);

             }

}

 

 

 

Step2:  Implementing the Interface

For receiving event callbacks from the main fragment class, the Activity must implement the interface that’s already been defined in the fragment class.

 

public static class MainActivity extends Activity implements

                                          MyFragment.OnHeadlinSelectedListener {

           public void onArticleSelected(int positon) {

       

    }

}

 

Step3: Deliver a Message to a fragment

 

Since the host activity can easily deliver messages to a fragment by capturing the fragment instance using findFragmentById() method, it is recommended to directly call the fragment’s

public methods

 

 

 

 

 

public static class MainActivity extends Activity implements

                                          MyFragment.OnHeadlinSelectedListener {

           public void onArticleSelected(int positon) {

 

 

          MyFragment frag = (MyFragment)                         getSupportFragmnetManager().findFragmentById(R.id.my_fragment);

              frag.doStuff()

 

 

 

This post is referred from Google docs Building a Dynamic UI with Fragments


In my next post, we are going to discuss how  Android app communicates with each other in Interacting one app to other app in android


Don't want to miss updates? Please click the below button!

Follow MindStick