我有下面的android代码。当我向前浏览标签时,它工作正常,但是当我尝试向后滑动时,应用程序崩溃了。 问题是在线“rootView =(ScrollView)gTabView.get(t);”当它尝试从全局变量第二次分配视图时。 我怎么能避免这个? 谢谢
public class DocPageActivity extends FragmentActivity {
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public static ActionBar actionBar = null;
public static int gtab=0;
public static ArrayList gTabView = new ArrayList();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
//InstState = savedInstanceState;
super.onCreate(savedInstanceState);
setContentView(R.layout.pager_obj);
gTabView.clear();
gtab = 0;
BuildTabsContents();//creates view to dislay in each tab in gTabView,store countNo of tabs in gtab
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home button should show an "Up" caret, indicating that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
/**
* A {@link android.support.v4.app.FragmentStatePagerAdapter} that returns a fragment
* representing an object in the collection.
*/
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return gtab;
}
@Override
public CharSequence getPageTitle(int position) {
return "TAB " + (position + 1);
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
Bundle args = getArguments();
int t = args.getInt(ARG_OBJECT);
rootView = (ScrollView) gTabView.get(t);
return rootView;
}
}
}
答案 0 :(得分:0)
我通过在类级别声明rootview并覆盖下面的方法来解决我的问题。
@Override
public void onDestroyView() {
super.onDestroyView();
if (rootView != null) {
ViewGroup parentViewGroup = (ViewGroup) rootView.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeAllViews();
}
}
}