You are on page 1of 7

SKR4307: Mobile Applications

Sem. II 2019/20
Lab 2c: Android Fragment
Week 2

Introduction

A Fragment represents a portion of a user interface or an operation that runs within


an Activity. A single activity can contain multiple fragments and many fragments can be
reused in many, different activities. It functions independently, but as it is linked to the
Activity, when an activity is destroyed, the fragment also gets destroyed. It is not wrong if we
say that a fragment is a type of sub-activity that can be utilized again in multiple activities.

Figure 1: Activity contains two fragments

Fragment usage

The 3 main usage of Fragments in Android, for which Fragments were introduced:

1. Modularity: If a single activity is having too many functional components, it’s better
to divide it into independent fragments, hence making the code more organized and
easier to maintain.

2. Reusability: If we define any particular feature in a fragment, then that feature more
or less becomes a reusable component which can be easily integrated into any
activity.

3. Adaptability: If we break UI components of an app screen into fragments, then it


becomes easier to change their orientation and placement, based on screen size etc.

1
PART I: Fragment Example

Figure 2: androidFragment apps

Application specifications

The app contains two Fragments and loading them by the clicking the buttons. The screen
display two Button’s those perform setOnClickListener event and a FrameLayout,
see Figure 2. On the click of First Button the First Fragment is being replaced and on click of
Second Button we replace the Second Fragment with the layout(FrameLayout). In the both
Fragment’s , display a TextView and a Button. The onclick of Button displays the
name of the Fragment with the help of Toast.

Step 1: Create a new Android project

1.1 Application name: androidFragment


1.2 Create an Empty Activity with the following configuration:
o Activity Name: MainActivity
o Layout Name: activity_main

Step 2: Configure the color and dimens files


2.1 Open res ->values ->colors.xml.
2.2 Update the existing colour’s specification that used in xml layout file with the
following color name and its hex value.

Color name Hex value


black #000
green #0f0
white #fff
button_background_color #925

2.3 Open res ->values ->dimens.xml.


2.4 Setting the screen design margins as following:

2
<resources>
<dimen name="horizontal_margin">16dp</dimen>
<dimen name="vertical_margin">16dp</dimen>
</resources>

Step 3: Modify the activity_main layout file by adding two buttons and framelayout.

3.1 The activity_main.xml layout file contain Buttons and FrameLayout


as shown in Figure 2. FrameLayout is designed to block out an area on the
screen to display a single item.

3.2 The main layout design structure for the screen is LinearLayout.

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

// Fill the attribute values


<!-- vertical orientation -->
<!—- horizontal_margin paddingLeft -->
<!-- vertical_margin paddingTop -->
<!—- horizontal_margin paddingRight -->
<!-- vertical_margin paddingBottom -->
<!— Main Activity context -->
>

// 1st button
<Button

<!—- firstFragment id -->


<!—- match parent layout_width -->
<!—- wrap_content layout_height -->
<!—- button_background_color background -->
<!—- string name first_fragment with text string “First
Fragment” text -->
<!—- white textColor -->
<!—- 20sp textSize -->
/>

// 2nd button
<Button

<!—- secondFragment id -->


<!—- match parent layout_width -->
<!—- wrap_content layout_height -->
<!—- button_background_color background -->
<!-— 10dp layout_marginTop -->
<!—- string name second_fragment with text string “Second
Fragment” text -->
<!—- white textColor -->
<!—- 20sp textSize -->
/>

// FrameLout
<FrameLayout
<!—- frameLayout id -->
<!—- match_parent layout_width and layout_height-->
<!—- 10 dp layout_marginTop -->

3
/>
</LinearLayout>

Both String names first_fragment and second_fragment with text string


First Segment and Second Segment respectively must be initialized in
string.xml file.

Step 4: Rewrite the MainActivity.java file by:

4.1 Add the code for initiate the Button’s defined in the layout file by perform the
setOnClickListener event.

4.2 On the click of First Button, the First Fragment is replaced and on click of Second
Button, the Second Fragment is replaced with the FrameLayout style.

4.3 To replace a Fragment with FrameLayout,create a Fragment Manager


(FragmentManager) and then begin the transaction using Fragment
Transaction (FragmentTransaction).

4.4 Ending Fragment (Fragment) replacement with the FrameLayout style.

public class MainActivity extends AppCompatActivity {

//1. Define two Button objects widget named btnFirst, btnSecond

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

//2. Map the the defined button objects to the GUI button
// defined in layout file

//3. Perform the setOnClickListener event on 1 st Button


object

//3.1 In onClick() method, load FirstFragment by


// calling the defined loadFragment() method

//4. Perform the setOnClickListener event on 2 nd Button


object

// 4.1 In onClick() method, load SecondFragment by


// calling the defined loadFragment() method
}

//5. loadFragment()

private void loadFragment(Fragment fragment) {


// Create a FragmentManager
FragmentManager fm = getFragmentManager();
// Create a FragmentTransaction to begin the transaction and
// replace the //Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// Replace the Framelayout with new Fragment

4
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commint(); // save the changes
}
}
Step 5: Fragments

5.1 Create two fragments and two xml layouts.

5.2 Right click on app package folder and create classes and name them as
FirstFragment and SecondFragment.

5.3 Modify the following code respectively.

5.3.1 FirstFragment.java
The FirstFragment class must extends from the Fragment class.
The Fragment inflates the layout and get the reference of Button. After
that, perform setOnClickListener event on Button so whenever
a user click on the button  a message “First Fragment“ is
displayed on the screen by using  a Toast.

public class FirstFragment extends Fragment {

//1. View and button objects definition


View view;
Button firstBtn;

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

//2. Inflate the layout for this fragment


view = inflater.inflate(R.layout.fragment_first,
container, false);

//3. Get the reference of Button


firstBtn =
(Button)view.findViewById(R.id.firstButton);

//4. perform setOnClickListener on first Button


firstBtn.setOnClickListener(new
View.OnClickListener() {
@Override

public void onClick(View v) {


//5. Display a message by using a Toast
Toast.makeText(getActivity(),"First Fragment",
Toast.LENGTH_LONG).show();
}
});
return view;
}
}

5.3.2 SecondFragment.java

The SecondFragment class must extends from the Fragment


class. The Fragment inflates the layout and get the reference of Button.
After that, perform setOnClickListener event on Button so

5
whenever a user click on the button  a message “Second
Fragment“ is displayed on the screen by using  a Toast.

5.4 Create two xml layouts files, as fragment_first and fragment_second.

5.4.1 Add the following code in respective files. In both files, design the
basic simple UI by using TextView and Button.

5.4.2 fragment_first layout file. The main layout design structure is


RelativeLayout.

<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.example.androidfragment.FirstFragment"
>

<!-- TextView and Button displayed in First Fragment -->


<!-- TextView -->
<!-- wrap_content layout_width and layout_height -->
<!-- true layout_centerHorizontal -->
<!-- 100dp layout_marginTop -->
<!-- black textColor -->
<!-- 25sp textSize -->
<!—- string name this_is_first_fragment with text
string “This is First Fragment” text -->

<!-- Button -->


<!-- firstButton id -->
<!-- fill_parent layout_width -->
<!-- wrap_content layout_height -->
<!-- true layout_centerInParent -->
<!-- 20dp layout_marginLeft -->
<!-- 20dp layout_marginRight -->
<!-- green background -->
<!-- white textColor -->
<!-- 20sp textSize -->
<!-- bold textStyle -->
<!—- string name first_fragment with text
string “First Fragment” text -->

5.4.3 fragment_second layout file. The main layout design structure is


RelativeLayout.

<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.example.androidfragment.SecondFragment"
>

<!-- TextView and Button displayed in Second Fragment -->


<!-- TextView -->
<!-- wrap_content layout_width and layout_height -->

6
<!-- true layout_centerHorizontal -->
<!-- 100dp layout_marginTop -->
<!-- black textColor -->
<!-- 25sp textSize -->
<!—- string name this_is_second_fragment with text
string “This is Second Fragment” text -->

<!-- Button -->


<!-- secondButton id -->
<!-- fill_parent layout_width -->
<!-- wrap_content layout_height -->
<!-- true layout_centerInParent -->
<!-- 20dp layout_marginLeft -->
<!-- 20dp layout_marginRight -->
<!-- green background -->
<!-- white textColor -->
<!-- 20sp textSize -->
<!-- bold textStyle -->
<!—- string name second_fragment with text
string “Second Fragment” text -->

The string names exist in both layout files (fragment_first and


fragment_second) must be initialized in string.xml file.

Step 6: Manifest file

6.1 Only one Activity (MainActivity) involved and it is already being defined.

6.2 Fragment don’t need to define the it in manifest because Fragment is a part of an
Activity.

Step 7: Run the app on the emulator/device

You might also like