android中在切换fragment时,怎样做到无需重复加载数据的方法。

private Fragment mContent;//定义了当前页面所在的fragmnet
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //初始化所要用到的fragment
    allFragment=RankItemFragment.newInstance("0","0");
    highFragment=RankItemFragment.newInstance("1","1");
    newFragment=RankItemFragment.newInstance("2","2");
    inFragment=RankItemFragment.newInstance("3","3");
    //放入初始默认的fragment
    fm = getActivity().getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.rankContent,allFragment).commit();
    mContent=allFragment;
}
//切换fragment时,不需要重新加载数据的方法
 private void switchContent(Fragment target) {
     if (mContent != target) {
         FragmentTransaction transaction = fm.beginTransaction();
         if (!target.isAdded()) {    // 先判断是否被add过
             //这里的每个fragment的布局都是放到id为rankContent的LinearLayout之上
             transaction.hide(mContent).add(R.id.rankContent, target).commit(); 
         } else {
             transaction.hide(mContent).show(target).commit(); // 隐藏当前的fragment,显示下一个
         }
         mContent=target;
     }
 }
 //点击切换,调用switchContent方法
 @Override
 public void onClick(View v) {
     switch (v.getId()) {
         case R.id.tv_allRank:
         switchContent(allFragment);
         break;
         case R.id.tv_highGood:
         switchContent(highFragment);
         break; 
         case R.id.tv_newGame:
         switchContent(newFragment);
         break;
         case R.id.tv_interest:
         switchContent(inFragment);
         break;
     }
 }

你可能感兴趣的:(android)