1、新建佈局文件,分別爲fragment1和fragment2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#FF0"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is the first fragment!" android:textSize="28sp" android:textColor="#000"/> </LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#0FF"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is the second fragment!" android:textSize="28sp" android:textColor="#F00"/> </LinearLayout>
2、添加Fragment1.java和Fragment2.java 代碼如下:
public class Fragment1 extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment1, container, false); } }
public class Fragment2 extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment2, container, false); } }
3、修改mainactivity.xml佈局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <fragment android:name="com.wxy.fragment.Fragment1" android:id="@+id/fragment1" android:layout_width="0px" android:layout_weight="1" android:layout_height="match_parent"/> <fragment android:name="com.wxy.fragment.Fragment2" android:id="@+id/fragment2" android:layout_width="0px" android:layout_weight="1" android:layout_height="match_parent"/> </LinearLayout>