You are on page 1of 10

Communication b/w Fragments

Fragment is a peace of Activity in android.

One Activity can have any no.of fragments. Each fragment have it's own
functionality.

All the fragmnets must be existed in one or more than one activity. Without
activity we can't show the fragment in android application.

Two frgments should never communicate directly.

The control of android fragment is handled by the activity which is having


the fragment.

The lifecycle of fragment is purely depends on activity lifecycle, which is


contains that fragment.

Using fragments we can utilize the device screen for multiple functionalities
shows at the same time.

In this Android Tutorial we learn about how communicate two fragments


within the same activity. For Example i have one activity that activity display two
differnet fragments. In first fragment, I will show the list of districts and in my
second fragment, It will display the details of individual district. when tap on first
fragment district list.

Create new Android Application project.


activity_main.xml
<LinearLayout
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:orientation="horizontal"
android:baselineAligned="false">
<fragment
android:id="@+id/listOfEmployees"
android:name="com.example.fragmentcommunication.fragments.ListOfEmployeesF
ragment"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<fragment
android:id="@+id/employeeDetais"
android:name="com.example.fragmentcommunication.fragments.EmployeeDetailsF
ragment"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"/>
</LinearLayout>

The name attribute is indicates fragment class in your android application.

andrid:laout_weight This is the attribute to align the fragments in android


activity. if you give layout_weight as 1 then it is first fragment it will show leftside
fo your screen. If you give layout_weight as 2 then it will show as second part in
your activity. It will show rightside of your screen.

Now crete a new layout for list of Districts. This is the fragment in your
android activity. The layout name is fragment_list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
android:id="@+id/listOfdists"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView

android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>

Now crete another new layout for display individual district details. This is the
fragment

in

your

android

activity.

The

layout

fragment_details_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/detailsView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

name

is

</LinearLayout>

Now create we need to create three two more classes for two fragment.

The first fragment is ListFragment.java. This fragment displays the list of


employees. And the second class is second fragment in our android application.
That class name is DetailsFragment.java.

Copy

below

code

into

your ListFragment.java class

in

your

application project.
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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;
public class ListFragment extends Fragment implements OnItemClickListener

android

{
private View v;
private static ListView lvOne;
private List<String> listOfDistricts;
private ArrayAdapter<String> adapter;
ListItemSelectedListener itemListerner;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
inflater

(LayoutInflater)getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.fragment_list_fragment, null, false);
addListItemsToListView();
initializeListeners();
return v;
}
@Override
public void onAttach(Activity activity)
{

super.onAttach(activity);
itemListerner = (ListItemSelectedListener)activity;
}
private void addListItemsToListView()
{
lvOne = (ListView)v.findViewById(R.id.list);
listOfDistricts = new ArrayList<String>();
listOfDistricts.add("Srikakulam");
listOfDistricts.add("Vijayanagaram");
listOfDistricts.add("Vizag");
adapter

new

ArrayAdapter<String>(getActivity(),

android.R.layout.simple_list_item_1, listOfDistricts);
lvOne.setAdapter(adapter);
}
private void initializeListeners()
{
lvOne.setOnItemClickListener(this);
}
public interface ListItemSelectedListener
{

public void listItemSelectedListener(String name);


}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
itemListerner.listItemSelectedListener(listOfDistricts.get(position));
}
}

In the above fragment we are use one Interface is


calledListItemSelectedListener. Because, We can not communicate directly two
fragments in android if you want communicate two fragemnts. we need to create
one interface in first Fragment and implement that interfac in Activity of that
fragment. And then create one public setter method in second Fragement and
assign the appropriate value to second fragment by using that public method.

itemListerner = (ListItemSelectedListener)activity; This peace of line


indicates the interface listerner register with the actiivty.

itemListerner.listItemSelectedListener(listOfDistricts.get(position));
This peace of code indicates the value set as a perameter to method of interface.
when implent the interface into activity. Then, you must override this method in
Activity register for this fragment.

Now create a new class with name DetailsFragment.java In this class it will
display the related content. Based on selected items in the first fragment. The
below code snippet is copy into your class.

DetailsFragment.java
package com.example.fragmentcommunication;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class DetailsFragment extends Fragment


{
private static TextView tvOne;
private View v;
Context context;
private static final String TAG = "DetailsFragment";
public void getItemValue(String itemName, Context context)
{
this.context = context;
tvOne.setText("Welcome to : "+itemName);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
inflater =
(LayoutInflater)getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SE
RVICE);

v = inflater.inflate(R.layout.fragment_details_fragment, null, false);


tvOne = (TextView)v.findViewById(R.id.detailsView);
onCreate(savedInstanceState);
return v;
}
}

In

the

above

code

snippet

we

are

write

one

method public

void

getItemValue(String itemName, Context context). The usage of this method


is to assign the selected value in the first fragment to second fragment using
activity.

Now Coming to MainActivity.java we will implement the interface. which is


declared in first fragment and assign the value getting from first activity and send it
to second fragment. So, copy the below code snippet intoMainActivity.java
package com.example.fragmentcommunication;
import
com.example.fragmentcommunication.ListFragment.ListItemSelectedListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
public class MainActivity extends FragmentActivity implements
ListItemSelectedListener{
public static final String TAG = "MainActiviyt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{

setContentView(R.layout.activity_main);
}
catch(Exception e)
{
Log.e(TAG, e.toString());
}
}
@Override
public void listItemSelectedListener(String name)
{
DetailsFragment detailsFragment = new DetailsFragment();
detailsFragment.getItemValue(name, this);
}
}

You might also like