Consider Using Fragments

frag.jpg

Fragments have been introduced in API 11, but still developers are struggling to understand their value and purpose. Theoretically saying fragments represents a behavior or portion of user Activity. We can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. So what are these Multi-Pane and Single Pane Layout? A panel or pane represents a part of the user interface.The term pane is a general term used to describe the concept that multiple views are combined into one compound view depending on the actual available space.

 

23232323232323232.jpg

If not enough space is available only one panel is shown. This is typically called a single-pane layout.

yytytyty.jpg

If more space is available, multi pane can be shown.

So Why Fragments (Instead of Activities)?

Something people often seem to not consider is how much ‘heavier’ activities are, and a (relatively) long break in the application flow can have a huge impact on how the app feels. Fragments load much faster, are much simpler and it’s easy to compose, animate and move them around. Lets say we have three activities :

  • Search Activity( To perform Search Operation )
  • Result Activity( To Display Search Result )
  • Show Detail Activity ( To Display the detail of each search result item )

If you are going to use just the activity for this, then it will be a nightmare plus it would bloat our codebase. But instead of using three separate activity to perform these activities we can use a single activity and have three fragments in it. For example a search fragment displays the search bar and communicates with Result Fragment to display the result. Then the Result Fragment communicates with Details Fragment to send data and Details Fragment would show the detail of the search item. Everything is done in a single activity and you can always switch between fragments with ease.

Okay then, How should I use them?

To use a fragment first of all we have to define them. To define a fragment we either extend  android.app.Fragment class or one of its subclasses like ListFragment, DialogFragment or WebViewFragment. Lets take a look at an example of fragment

package somegeekguy.anothershityapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class AnotherFragment extends Fragment {


    public AnotherFragment() {
       
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_another, container, false);
    }

}

After defining a fragment we need to include fragment in our layout.xml file. We can statically define fragment in our xml or dynamically define them in our activity.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


</LinearLayout>

Now in the activity you can use FragmentManager to replace the container with this fragments. Lets take a look at the code.

FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, new SearchBarFragment());
ft.commit();

Above code will add SearchBarFragment to searchbarcontainer in our layout. Now after we input search text to the fragemnt and press search button, it will need to display the list of search result in ResultFragment. To do that we need to replace the fragment.

FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, new ResultListFragment());
ft.commit();

Again if we need to display the search detail we can replace the container with SearchDetailFragment . If we need to check which activity is displaying right now then we can perform following operation :

Fragment fragment = fm.findFragmentById(R.id.your_placehodler);

To remove fragment from the container :

FragmentTransaction ft = fm.beginTransaction();
ft.remove(fragment);
ft.commit();

So that’s easy right? Hell Yeah!. So now what if we want to backtrack our application through fragment. We can navigate back throgh our activity with back button. In case of fragment we need to add our fragment to the backstack.

FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.searchbarcontainer, new SearchBarFragment());
ft.addToBackStack()
ft.commit();

Fragment Lifecycle

fragment_lifecycle.png

Wrapping Up!

Fragments are a powerful feature of the Android platform and like a Swiss watch have a lot of sophistication and complexity behind them. But just like that Swiss watch, you don’t have to understand all of that sophistication and complexity to begin taking advantage of them. Lets talk about the important points on why you should start using fragments

  • No need to litter the manifest with activity definition anymore.
  • Dealing with different device form factors
  • Centralized Management
  • Information sharing between app screens
  • Less heavier than activities

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s