多个fragment切换,而不重新加载数据的实现
1、在xml中添加一个framlayout
<FrameLayout
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp" />
2、初始化所有fragment,并添加一个fragment显示
private void initFragment() {
allfragment = new Ts_All_Fragment();
unstartfragment = new Ts_unstart_Fragment();
finishfragment = new Ts_finish_Fragment();
startfragment = new Ts_start_Fragment();
mFragmentMan = getSupportFragmentManager();
FragmentTransaction ft = mFragmentMan.beginTransaction();
ft.add(R.id.framelayout,startfragment).commit();
mContent = startfragment;
}
3、当点击控件时,切换fragment 调用下面的方法
public void switchContent(Fragment to) {
if (mContent != to) {
FragmentTransaction transaction = mFragmentManager.beginTransaction().setCustomAnimations(
android.R.anim.fade_in, android.R.anim.fade_out);
// 先判断是否被add过
if (!to.isAdded()) {
// 隐藏当前的fragment
transaction.hide(mContent).add(R.id.framelayout, to).commit();
}else {
transaction.hide(mContent).show(to).commit(); //提交
}
mContent = to;
}
}
4、在监听方法中调用即可:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ts_activity_tv1:
switchContent( allfragment);
break;
case R.id.ts_activity_tv2:
switchContent( unstartfragment);
break;
case R.id.ts_activity_tv3:
switchContent( startfragment);
break;
case R.id.ts_activity_tv4:
switchContent(finishfragment);
break;
default:
break;
}