防止每次切换radio button重复加载fragment

发现Index中使用radiobutton+Fragment并不是想象中的用Fragment的replace实现切换。这样的确会造成切换的时候重新初始化加载网络数据啥的。特别是Fragment里面的数据很复杂的时候。而是这样:

   Fragmentfragment = (Fragment)mFragmentPagerAdapter

.instantiateItem(mContainer, R.id.rb_microstore);

mFragmentPagerAdapter.setPrimaryItem(mContainer,0, fragment);

mFragmentPagerAdapter.finishUpdate(mContainer);


privateFragmentPagerAdaptermFragmentPag


erAdapter=newFragmentPagerAdapter(

getSupportFragmentManager()) {

@Override

public voidsetPrimaryItem(ViewGroup container,intposition, Object object) {

currentPosition= position;

super.setPrimaryItem(container, position, object);

}

@Override

publicFragment getItem(intposition) {

switch(position) {

caseR.id.rb_discover:

return newDiscoverFrag();

caseR.id.rb_circle:

return newCircleFrag();

caseR.id.rb_myinfo:

return newPersonalCenterFrag();

caseR.id.rb_microstore:

default:

return newMicroStoreFrag();

}

}

@Override

public intgetCount() {

return4;

}

};


实现checkchangeListener

@Override

public voidonCheckedChanged(CompoundButton buttonView,booleanisChecked) {

if(isChecked) {

Fragment fragment = (Fragment)mFragmentPagerAdapter

.instantiateItem(mContainer, buttonView.getId());

mFragmentPagerAdapter.setPrimaryItem(mContainer,0, fragment);

mFragmentPagerAdapter.finishUpdate(mContainer);

}

}

这样不会多次创建各种Fragment。也会很流畅。这样需要在Fragment中重写

@Override

public voidsetMenuVisibility(booleanmenuVisible) {

super.setMenuVisibility(menuVisible);

if(this.getView() !=null)

this.getView().setVisibility(menuVisible ? View.VISIBLE: View.GONE);

}

否则会导致重影。哈哈。今天就遇到了

你可能感兴趣的:(防止每次切换radio button重复加载fragment)