###布局
<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" >
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="button1"
android:text="大陆明星" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="button2"
android:text="欧美明星" />
</LinearLayout>
<FrameLayout
android:id="@+id/fl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/ll" >
</FrameLayout>
</RelativeLayout>
###自定义fragment1 fragment2
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="大陆明星"
/>
###自定义fragment2
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="欧美明星"
/>
###MainActivity
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 得到FragmentManager fargment管理者对象
fragmentManager = getSupportFragmentManager();
// 开启事务,得到事务对象
FragmentTransaction beginTransaction = fragmentManager
.beginTransaction();
//得到fragment对象
fragment1 = new Fragment1();
fragment2 = new Fragment2();
// 替换fragment
// beginTransaction.replace(R.id.fl, new Fragment1());
// 同时添加两个fragment
beginTransaction.add(R.id.fl,fragment1).add(R.id.fl,fragment2);
// 提交事务
beginTransaction.commit();
}
public void button1(View v) {
// 开启事务,得到事务对象
FragmentTransaction beginTransaction = fragmentManager
.beginTransaction();
// 替换fragment
// beginTransaction.replace(R.id.fl, new Fragment1());
//点击大陆明星时,隐藏欧美明星,展示出大陆明星
beginTransaction.hide(fragment2).show(fragment1);
// 提交事务
beginTransaction.commit();
}
public void button2(View v) {
// 开启事务,得到事务对象
FragmentTransaction beginTransaction = fragmentManager
.beginTransaction();
// 替换fragment
// beginTransaction.replace(R.id.fl, new Fragment2());
//点击欧美明星时,展示欧美明星,隐藏出大陆明星
beginTransaction.hide(fragment1).show(fragment2);
// 提交事务
beginTransaction.commit();
}
}