不能用 replace 应该是 add
replace()的调用会导致Fragment的onCreteView()被调用,所以切换界面时会无法保存当前的状态。因此一般采用add()、hide()与show()配合,来达到保存Fragment的状态。
1 推荐使用,考虑到回栈因素,效率更好
可以把一个fragment保存到返回栈中
通过显示隐藏来处理:
int tabIndex=0,tag=0;
fragment[] fragments=new fragment[]{A.class,B.class,C.class,D.class};
Fragment newFragment = fragments[tag];
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!getSupportFragmentManager().getFragments().contains(fragments[tag])) {
transaction.add(R.id.main_content, newFragment);
}
transaction.addToBackStack(null);
transaction.hide(fragments[tabIndex]);
transaction.show(newFragment);
transaction.commit();
tabIndex = tag;
2 相对来说比较复杂,这个更适合保存数据的,意外等适合这个
FragmentPagerAdapter可以将很多个Fragment保存起来以供取出,并且封装了取出的接口,其实还是通过FragmentTransaction来实现的。
package com.nmbb.sample.fragmentswitch;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.RadioButton;
public class MainActivity extends FragmentActivity implements
OnCheckedChangeListener, OnClickListener {
private RadioButton mTab1;
private RadioButton mTab2;
private RadioButton mTab3;
private RadioButton mTab4;
private RadioButton mTab5;
private FrameLayout mContainer;
public CompoundButton currentButtonView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTab1 = (RadioButton) findViewById(R.id.radio_button0);
mTab2 = (RadioButton) findViewById(R.id.radio_button1);
mTab3 = (RadioButton) findViewById(R.id.radio_button2);
mTab4 = (RadioButton) findViewById(R.id.radio_button3);
mTab5 = (RadioButton) findViewById(R.id.radio_button4);
mContainer = (FrameLayout) findViewById(R.id.container);
mTab1.setOnCheckedChangeListener(this);
mTab2.setOnCheckedChangeListener(this);
mTab3.setOnCheckedChangeListener(this);
mTab4.setOnCheckedChangeListener(this);
mTab5.setOnCheckedChangeListener(this);
mTab1.setOnClickListener(this);
mTab2.setOnClickListener(this);
mTab3.setOnClickListener(this);
mTab4.setOnClickListener(this);
mTab5.setOnClickListener(this);
mTab1.performClick();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Fragment fragment = (Fragment) mFragmentPagerAdapter
.instantiateItem(mContainer, buttonView.getId());
mFragmentPagerAdapter.setPrimaryItem(mContainer, 0, fragment);
mFragmentPagerAdapter.finishUpdate(mContainer);
}
}
private FragmentPagerAdapter mFragmentPagerAdapter = new FragmentPagerAdapter(
getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
switch (position) {
case R.id.radio_button1:
return FragmentTest.instantiation(2);
case R.id.radio_button2:
return FragmentTest.instantiation(3);
case R.id.radio_button3:
return FragmentTest.instantiation(4);
case R.id.radio_button4:
return FragmentTest.instantiation(5);
case R.id.radio_button0:
default:
return FragmentTest.instantiation(1);
}
}
@Override
public int getCount() {
return 5;
}
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
instantiateItem从FragmentManager中查找Fragment,找不到就getItem新建一个,setPrimaryItem设置隐藏和显示,最后finishUpdate提交事务。
mContainer就是xml中的FrameLayout。
package com.nmbb.sample.fragmentswitch;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTest extends Fragment {
public static FragmentTest instantiation(int position) {
FragmentTest fragment = new FragmentTest();
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
text1.setText("Fragment " + getArguments().getInt("position", 1));
}
@Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (this.getView() != null)
this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
}
}
其中,下面的代码很关键,没有下面的代码会出现切换tab的时候重影现象:
@Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (this.getView() != null)
this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
}
问题的出现正是因为使用了Fragment的状态保存,当系统内存不足,Fragment的宿主Activity回收的时候,Fragment的实例并没有随之被回收。Activity被系统回收时,会主动调用onSaveInstance()方法来保存视图层(View Hierarchy),所以当Activity通过导航再次被重建时,之前被实例化过的Fragment依然会出现在Activity中,然而从上述代码中可以明显看出,再次重建了新的Fragment,综上这些因素导致了多个Fragment重叠在一起。
我尝试了很多种方法去解决这个问题,比如:
在onSaveInstance()里面去remove()所有非空的Fragment,然后在onRestoreInstanceState()中去再次按照问题一的方式创建Activity。当我处于打开“不保留活动”的时候,效果非常令人满意,然而当我关闭“不保留活动”的时候,问题却出现了。当转跳到其他Activity、打开多任务窗口、使用Home回到主屏幕再返回时,发现根本没有Fragment了,一篇空白。
于是跟踪下去,我调查了onSaveInstanceState()与onRestoreInstanceState()这两个方法。原本以为只有在系统因为内存回收Activity时才会调用的onSaveInstanceState(),居然在转跳到其他Activity、打开多任务窗口、使用Home回到主屏幕这些操作中也被调用,然而onRestoreInstanceState()并没有在再次回到Activity时被调用。而且我在onResume()发现之前的Fragment只是被移除,并不是空,所以就算你在onResume()中执行问题一中创建的Fragment的方法,同样无济于事。所以通过remove()宣告失败。
接着通过调查资料发现Activity中的onSaveInstanceState()里面有一句super.onRestoreInstanceState(savedInstanceState),Google对于这句话的解释是“Always call the superclass so it can save the view hierarchy state”,大概意思是“总是执行这句代码来调用父类去保存视图层的状态”。其实到这里大家也就明白了,就是因为这句话导致了重影的出现,于是我删除了这句话,然后onCreate()与onRestoreInstanceState()中同时使用问题一中的创建Fragment方法,然后再通过保存切换的状态,发现结果非常完美。代码如下:
//记录Fragment的位置
private int position = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
setTabSelection(position);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
position = savedInstanceState.getInt("position");
setTabSelection(position);
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
//记录当前的position
outState.putInt("position", position);
}
3 最简单的使用
/**
* 切换选中的item
* Add Show
*
* @param mToTab
*/
private void setCurrentItem(int mToTab) {
// 隐藏所有Fragment
FragmentTransaction transaction = manager.beginTransaction();
hideFragments(transaction);
switch (mToTab) {
case TAB_HOME:
if (null == mHomeFragment) {
mHomeFragment = new HomeFragment();
transaction.add(R.id.content, mHomeFragment);
} else {
transaction.show(mHomeFragment);
}
break;
// case TAB_ORDER:
// if (null == mOrderFragment) {
// mOrderFragment = new OrderFragment();
// transaction.add(R.id.content, mOrderFragment);
// } else {
// transaction.show(mOrderFragment);
// }
// break;
// case TAB_SHOP:
// if (null == mShoppingFragment) {
// mShoppingFragment = new ShoppingFragment();
// transaction.add(R.id.content, mShoppingFragment);
// } else {
// transaction.show(mShoppingFragment);
// }
// break;
case TAB_SELF:
if (null == mPersonalCenterFragment) {
mPersonalCenterFragment = new PersonalCenterFragment();
transaction.add(R.id.content, mPersonalCenterFragment);
} else {
transaction.show(mPersonalCenterFragment);
}
break;
case -1:
new RuntimeException();
break;
}
transaction.commitAllowingStateLoss();
}
/**
* 隐藏所有的fragment避免数据错乱或者不见
*
* @param transaction
*/
private void hideFragments(FragmentTransaction transaction) {
if (null != mHomeFragment) {
transaction.hide(mHomeFragment);
}
// if (null != mOrderFragment) {
// // transaction.hide(mOrderFragment);
// }
// if (null != mShoppingFragment) {
// // transaction.hide(mShoppingFragment);
// }
if (null != mPersonalCenterFragment) {
transaction.hide(mPersonalCenterFragment);
}
}