Two fragments in one activity

Carlos Gómez
devops and cross platform development
6 min readApr 26, 2014

--

A fragment represents a portion of user interface in an Activity, and provides a mechanism for creating reusable modules, after being created this module can be embedded within activities. In this example we will combine two fragments in an activity and follow the steps for the creation and use of fragments, as well as the implementation of the communication between the two fragments within an activity.

Explain fragments in android

Funcitonality of the Two Fragments Application

The UI for the first fragment will contain an EditText view and a Button and the second fragment will contain a TextView object. The two fragments will be embedded within the main activity of the application and when the button in the first fragment is pressed, the text entered into the EditText view will appear on the TextView of the second fragment.

Creating the Project

Launch Eclipse and create an Android Application Project named TwoFragments with the appropriate package name and SDK selections. Select blank activity then on the New Blank Activity screen of the Android Application wizard, set the Activity Name to TwoFragmentsActivity and the Layout Name to activity_twofragments.

Adding the Android Support Library

The support for fragments was not introduced until Android 3.0. The purpose of the Android Support Library is to make features that were introduced in later versions of Android available to applications that need to be compatible with earlier Android versions.

Lets verify that we have the Android Support Library package installed, in Eclipse select the Window -> Android SDK Manager menu option. When the manager window has appeared on the screen, scroll down to the Extras section and make sure that Android Support Library item is listed as Installed. Then we need to check that the library is in our project in the lib folder.

Library that support fragments

First Fragment

Creating the First Fragment Layout

Right-click on the layout package under res and selecting the New → Other.. → Android → Android XML Layout → give the name one_fragment.xml → Root Element list, select RelativeLayout and click Finish. Modify the xml fragment view:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/buttonChange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textOneFragment"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="@string/buttonChange" />
<EditText
android:id="@+id/textOneFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
</RelativeLayout>Creating the First Fragment ClassAditionally to a UI layout, a fragment also needs to have a class associated with it to do the work behind the scenes. Add a class in the package name of the project (in this example com.devcfgc.twofragments) of the src folder, right-clicking on the package and select the New → Class → Name OneFragment → in Superclass browse to locate the Fragment - android.support.v4.app → FinishThe first change is override the onCreateView() method to make sure the layout file is inflated and displayed when the fragment is used within an activity.package com.devcfgc.twofragments;import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OneFragment extends Fragment {@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.one_fragment, container, false);
return view;
}
}Second Fragment

Creating the Second Fragment Layout

Add a new Android XML Layout file to the project, once again selecting the options to create a layout resource file with a RelativeLayout as the root element. Name the file two_fragment.xml and click Finish. Modify the XML to add a TextView to the fragment layout as follows:<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textChanged"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/textChange"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>Creating the Second Fragment ClassAs with the first fragment, this one will also need to have a class associated with it. Add a class in the package name of the project (in this example com.devcfgc.twofragments) of the src folder, right-clicking on the package and select the New → Class → Name TwoFragment → in Superclass browse to locate the Fragment - android.support.v4.app → FinishThen override the onCreateView() method:package com.devcfgc.twofragments;import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TwoFragment extends Fragment {@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.two_fragment, container, false);
return view;
}
}Adding the Fragments to the ActivityFirst we need to add the fragments to the main activity layout, open the activity_two_fragments.xml and embed the two fragments as follows:<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"
tools:context="com.devcfgc.twofragments.TwoFragmentsActivity">
<fragment
android:id="@+id/one_fragment"
android:name="com.devcfgc.twofragments.OneFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="@layout/one_fragment" />
<fragment
android:id="@+id/two_fragment"
android:name="com.devcfgc.twofragments.TwoFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="@layout/two_fragment" />
</RelativeLayout>
Example android layout two fragments
When the user touches the button in the one fragment UI, the one fragment class is going to need to get the text from the EditText view send them to the two fragment UI. We are going to use the activity to communicate the two fragments.Edit OneFragment.java:package com.devcfgc.twofragments;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.Button;
import android.widget.EditText;
public class OneFragment extends Fragment {private static EditText mEditText;OneFragmentListener activityCallback;//Listener for onButtonClick UI
public interface OneFragmentListener {
public void onButtonClick(String text);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (OneFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OneFragmentListener");
}
}
//We get the reference to the editText and the button setUp the OnClickListener
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.one_fragment, container, false);
mEditText = (EditText) view.findViewById(R.id.textOneFragment);final Button button = (Button) view.findViewById(R.id.buttonChange);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
//Set the activityCallback to onButtonClick passing the text in the mEditText
public void buttonClicked(View view) {
activityCallback.onButtonClick(mEditText.getText().toString());
}
}
Next step, edit the TwoFragment.java. Within the TextFragment class we will now implement a public method named changeTextProperties() which takes as argument a string for the new text to be displayed. The method will then use these values to modify the TextView object.
package com.devcfgc.twofragments;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 TwoFragment extends Fragment {private static TextView mTextView;@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.two_fragment, container, false);
mTextView = (TextView) view.findViewById(R.id.textChanged);
return view;
}
public void changeTextProperties(String text) {
mTextView.setText(text);
}
}
Next step, edit the TwoFragmentsActivity.java. The activity needs to extends from FragmentActivity instead of Activity since the Android Support Library is being used for fragment support. When the TwoFragment was placed in the layout of the activity, it was given an ID of two_fragment. Using this ID, it is now possible for the activity to obtain a reference to the fragment instance and call the changeTextProperties() method on the object.
package com.devcfgc.twofragments;import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class TwoFragmentsActivity extends FragmentActivity implements
OneFragment.OneFragmentListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two_fragments);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.two_fragments, menu);
return true;
}
@Override
public void onButtonClick(String text) {
TwoFragment textFragment = (TwoFragment) getSupportFragmentManager()
.findFragmentById(R.id.two_fragment);
textFragment.changeTextProperties(text);
}
}
Use two android fragments in one activity
Check the source code in github: https://github.com/devcfgc/TwoFragments-Android

--

--

Cloud/Software Architect and DevOps learning about #devops, #cloud, #netcore, #microservices and #newtech