1. Using Eclipse, create a new Android project and name it Fragments.
2. In the res/layout folder, add a new file and name it fragment1.xml. Populate it with the following:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orientation=”vertical” android:layout_width=”fill_parent” android:layout_height=”fill_parent” 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. Also in the res/layout folder, add another new file and name it fragment2.xml. Populate it as follows:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orientation=”vertical” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:background=”#FFFE00”
>
<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=”net.learn2develop.Fragments.Fragment1” android:id=”@+id/fragment1”
android:layout_weight=”1” android:layout_width=”0px” android:layout_height=”match_parent” />
<fragment android:name=”net.learn2develop.Fragments.Fragment2” android:id=”@+id/fragment2”
android:layout_weight=”1” android:layout_width=”0px” android:layout_height=”match_parent” />
</LinearLayout>
5. Under the net.learn2develop.Fragments package name, add two Java class files and name them Fragment1.java and Fragment2.java (see Figure 2-18).
FIGURE 2-18
6. Add the following code to Fragment1.java:
package net.learn2develop.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. Add the following code to Fragment2.java:
package net.learn2develop.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);
}
}
Không có nhận xét nào:
Đăng nhận xét