android的fragment使用中static静态fragment实例遇到的坑
场景描述:
FragmentActivity + viewpager + fragment
问题描述:
FragmentActivity finish过后 由于static的类变量还存在 没有销毁 导致多次启动应用 fragment 多次运行
代码片段:
宿主片段:
TabFragmentAdapter tfa = new TabFragmentAdapter( getSupportFragmentManager(), this, new GezitechFragment[]{FragmentBookShelf_.newIntent(),FragmentBookShop_.newIntent()}, getResources().getStringArray(R.array.tab_arr) ) ;
pager.setOffscreenPageLimit(2);
pager.setAdapter( tfa );
// 定义 SlidingTabLayout
stl.setDistributeEvenly(true);
stl.setSelectedIndicatorColors(getResources().getColor(R.color.white));
stl.setBackgroundColor(getResources().getColor(R.color.c_title_bg));
stl.setCustomTabView(R.layout.read_tab_item_view, R.id.tv_tab_item_des);
stl.setViewPager( pager ); // 加载ViewPager
fragment 片段:
static FragmentBookShelf_ _this = null;
public static FragmentBookShelf_ newIntent() {
if (_this == null) {
_this = new FragmentBookShelf_();
}
return (FragmentBookShelf_) _this;
}
解决办法:
在fragment中 ondestroty 销毁时 将 _this的值赋值为NULL 即可解决 finish 没有销毁的情况。。。
void onDestroty(){
_this = null;_
super.onDestroty();
}
场景描述:
FragmentActivity + viewpager + fragment
问题描述:
FragmentActivity finish过后 由于static的类变量还存在 没有销毁 导致多次启动应用 fragment 多次运行
代码片段:
宿主片段:
TabFragmentAdapter tfa = new TabFragmentAdapter( getSupportFragmentManager(), this, new GezitechFragment[]{FragmentBookShelf_.newIntent(),FragmentBookShop_.newIntent()}, getResources().getStringArray(R.array.tab_arr) ) ;
pager.setOffscreenPageLimit(2);
pager.setAdapter( tfa );
// 定义 SlidingTabLayout
stl.setDistributeEvenly(true);
stl.setSelectedIndicatorColors(getResources().getColor(R.color.white));
stl.setBackgroundColor(getResources().getColor(R.color.c_title_bg));
stl.setCustomTabView(R.layout.read_tab_item_view, R.id.tv_tab_item_des);
stl.setViewPager( pager ); // 加载ViewPager
fragment 片段:
static FragmentBookShelf_ _this = null;
public static FragmentBookShelf_ newIntent() {
if (_this == null) {
_this = new FragmentBookShelf_();
}
return (FragmentBookShelf_) _this;
}
解决办法:
在fragment中 ondestroty 销毁时 将 _this的值赋值为NULL 即可解决 finish 没有销毁的情况。。。
void onDestroty(){
_this = null;_
super.onDestroty();
}