Dynamically add Fragments to an Activity in a Legacy Android Version

June 30, 2012
By

Android begins to support fragments from the version 3.0 onwards. In those versions prior to 3.0, we have to use Android Support Library to create fragments. In this article we will create an application which adds a fragment to the main activity at runtime in Android version 2.3 using Android Support Library.


1. Create a new Android Project namely “DynamicFragmentsForLegacy”

New Android Project

Figure 1: New Android Project


2. Select Android Build Target 2.3 for this application

Select Android Build Target

Figure 2: Select Android Build Target


3. Enter application details

Enter Application Details

Figure 3: Enter Application Details


4. Add Android Support Library

Android supports fragments from the version 3.0 onwards only. Android provide and external support library to use fragments in the versions prior to 3.0. In order to add this library to our project in eclipse, right click “DynamicFragmentsForLegacy”(ProjectExplorer) -> Android Tools -> Add Support Library.


5. res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">DynamicFragmentsForLegacy</string>
    <string name="str_btn_load">Load Fragment</string>
    <string name="str_tv_fragment">This is a fragment</string>

</resources>


6. res/layout/hello_fragment_layout.xml


<?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="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_tv_fragment"
    />
</LinearLayout>


7. src/in/wptrafficanalyzer/dynamicfragmentslegacy/HelloFragment.java


package in.wptrafficanalyzer.dynamicfragmentslegacy;

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

public class HelloFragment extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_fragment_layout, null);
        return v;
    }
}


8. res/layout/main.xml


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

    <Button
        android:id="@+id/btn_load"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_load" />

    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
     >
     </LinearLayout>

</LinearLayout>


9. src/in/wptrafficanalyzer/dynamicfragmentslegacy/MainActivity.java


package in.wptrafficanalyzer.dynamicfragmentslegacy;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends FragmentActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                Fragment hello = new HelloFragment();
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.add(R.id.fragment_container,hello);

                fragmentTransaction.commit();

            }
        };

        Button btnLoad = (Button) findViewById(R.id.btn_load);
        btnLoad.setOnClickListener(listener);

    }
}


10. Execute the application

Main Activity

Figure 4: Main Activity

  • On clicking the button “Load Fragment” of the Figure 4, a fragment will be loaded at in the same activity as shown in the Figure 5.

Main Activity with a dynamically loaded Fragment

Figure 5: Main Activity with a dynamically loaded Fragment


11. Download


12. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner