CS4521:   Mobile and Topics in Web Programming



Solution

Exercise 4.2- Fragments (not turned in)

Do the Try It Out "Using Fragements" Exercise in your book pages 70-73.

 

1) Create project named Fragments

 

2) In the res/layout folder, add a new file and name it fragment1.xml and enter the following

<?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"
android:background="#00FF00">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is fragment #1"
android:textColor="#000000"
android:textSize="25sp" />

</LinearLayout>

3) in res/layout folder add the following fragment2.xml code:

<?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"
android:background="#FFEE00">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is fragment #2"
android:textColor="#000000"
android:textSize="25sp" />

</LinearLayout>

4) In main.xml add the following code in bold

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

<fragment
android:name="grewe.fragments.Fragment1"
android:id="@+id/fragment1"
android:layout_width="0px"
android:layout_weight="1"
android:layout_height="match_parent"
/>
<fragment
android:name="grewe.fragments.Fragment2"
android:id="@+id/fragment2"
android:layout_width="0px"
android:layout_weight="1"
android:layout_height="match_parent"
/>


</LinearLayout>

 

5) Under the add 2 java class files called Fragment1.java and Fragment2.java

6) Fragment1.java contains:

package grewe.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
      //----inflate the layout for this fragment --
      return inflater.inflate(R.layout.fragment1,container, false);
}

}

7) Fragment2.java contains:

package grewe.fragments;

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

public class Fragment2 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      //----inflate the layout for this fragment --
     return inflater.inflate(R.layout.fragment2,container, false);
}

}

 

8) Run the application

© Lynne Grewe