Android FragmentTransactions - Show Dynamic Fragments With ListViews


In this simple example here,we shall be seeing how to perform a fragment transaction on dynamic fragments.

By dynamic we mean that our Fragments get created programmatically at runtime as opposed to using XML Layouts.

We shall simply replace our layout with two fragments,each with its own layout and with simple ListViews.Take note our fragments are created dynamically on code,then we replace them and commit the transaction.

Section 1 : Fragment One Class

  • Contains a simple listview in its layout.

 

package com.tutorials.dynamicfragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Fragment1 extends Fragment{

  ListView lv;
  ArrayAdapter<String> adapter;
  String[] names={"Daley Blind","Chrid Smalling","Matteo Darmian","Luke Shaw"};

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

    View rootView=inflater.inflate(R.layout.fragment1, container,false);

    lv=(ListView) rootView.findViewById(R.id.listView1);
    adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,names);
        lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> arg0, View v, int pos,
          long id) {
        // TODO Auto-generated method stub

        Toast.makeText(getActivity(), names[pos], Toast.LENGTH_SHORT).show();
      }
    });

    return rootView;
  }

}

   

Section 2 : Fragment Two Class

  • Contains a simple listview in its layout.

 

package com.tutorials.dynamicfragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Fragment2 extends Fragment{

ListView lv;
ArrayAdapter<String> adapter;
    String[] positions={"Midfielder","Defender","FullBack","Forward","Mid","Winger","FullBack","Winger","CenterBack"};

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

    View rootView=inflater.inflate(R.layout.fragment2, container,false);

    lv=(ListView) rootView.findViewById(R.id.listView1);
    adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,positions);

    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
          long id) {
        // TODO Auto-generated method stub
        Toast.makeText(getActivity(), positions[pos], Toast.LENGTH_SHORT).show();
      }
    });

    return rootView;
  }

}

   

Section 3 : MainActivity Class

  • We perform and commit Fragment Transactions.

 

package com.tutorials.dynamicfragments;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //WE NEED FRAGMENT MANAGER ASSOCIATED WITH THIS ACTIVITY
        FragmentManager fm=getFragmentManager();

        //LETS START FRAGMENT TRANSACTION
        FragmentTransaction ft=fm.beginTransaction();

        //INSTANTIATE OUR TWO FRAGEMNTS
        Fragment f1=new Fragment1();
        Fragment f2=new Fragment2();

        //LETS REPLACE FISRT OUR MAIN LAYOUT THEN THE LINEAR LAYOUT INSIDE IT WITH OUR RESPECTIVE FRAGMENTS
        ft.replace(android.R.id.content, f1);
        ft.replace(R.id.content2, f2);

        //IT WAS A TRANSACTION SO WE COMMIT IT
       ft.commit();

    }

}

   

Section 4 : Layouts

(a). ActivityMain.xml
  • Contains layouts we shall be replacing.

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#009968"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/content2"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="22dp"
        android:background="#2fc1b9"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>
(b). Fragment1 Layout  
<?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" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>
(c). Fragment 2 Layout  
<?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" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

  Cheers.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post