本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/
fragment的真正用处是在程序运行过程中动态地添加。
1. 新建工程。
2. res/layout/main.xml
- <?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" >
-
- </LinearLayout>
3. res/layout/fragment1.xml
- <?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:background="#00FF00"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/lblFragment1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="This is fragment #1"
- android:textColor="#000000"
- android:textSize="25sp" />
-
- </LinearLayout>
4. res/layout/fragment2.xml
- <?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:background="#FFFE00"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="This is fragment #2"
- android:textColor="#000000"
- android:textSize="25sp" />
-
- </LinearLayout>
5. Fragment1.java
- public class Fragment1 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
-
- return inflater.inflate(R.layout.fragment1, container, false);
- }
- }
6. Fragment2.java
- public class Fragment2 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
-
- return inflater.inflate(R.layout.fragment2, container, false);
- }
- }
7. FragmentsActivity.java
- public class FragmentsActivity extends Activity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- FragmentManager fragmentManager = getFragmentManager();
- FragmentTransaction fragmentTransaction = fragmentManager
- .beginTransaction();
-
-
- WindowManager wm = getWindowManager();
- Display d = wm.getDefaultDisplay();
- if (d.getWidth() > d.getHeight()) {
-
- Fragment1 fragment1 = new Fragment1();
-
-
- fragmentTransaction.replace(android.R.id.content, fragment1);
- } else {
-
- Fragment2 fragment2 = new Fragment2();
- fragmentTransaction.replace(android.R.id.content, fragment2);
- }
-
- fragmentTransaction.addToBackStack(null);
- fragmentTransaction.commit();
-
- }
-
- }
8. 调试。


[转]动态添加Fragments
原文:http://www.cnblogs.com/xunbu7/p/4989598.html