我有一个使用 SlidingMenu、Action Bar Sherlock 的应用程序,现在我正在尝试重写我以前的代码,以使用 Android 4.2 版本中支持库中引入的嵌套片段。
问题是,当我在片段中滑动时,它们会在一瞬间可见,然后消失(黑屏)。有时它们停留在屏幕上,有时屏幕全黑,片段根本不出现。我怀疑我对片段生命周期缺乏了解,但我真的看不到这里的错误。
刷过它们会给我带来不同的结果。在初始加载时,第一个片段是黑色的。如果我滑动到 nr 4 并返回到 nr 1,那么 nr 1 片段就可以了。如果我快速滑动到 nr 2 然后再到 nr 1,nr 1 又是黑色的。如果我从 nr 2 缓慢滑动到 nr 1,则 nr 1 保持正常:-/
这是我的代码:
public class LeagueInfoFragment extends SherlockFragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container != null) {
container.removeAllViews();
}
setRetainInstance(true);
setHasOptionsMenu(true);
mExampleId = getArguments().getInt("mExampleId");
View view = inflater.inflate(R.layout.viewpager_tournament, container,
false);
ViewPager awesomePager = (ViewPager) view.findViewById(R.id.pager);
awesomePager.setAdapter(new ExamplePagerAdapter(this, getChildFragmentManager(), createFragments()));
TabPageIndicator titleIndicator = (TabPageIndicator) view
.findViewById(R.id.titles);
titleIndicator.setViewPager(awesomePager);
return view;
}
private List<Fragment> createFragments() {
List<Fragment> list = new ArrayList<Fragment>();
list.add(LeagueTableFragment.newInstance(0));
list.add(FixturesFragment.newInstance(1));
list.add(NewsFragment.newInstance(2));
list.add(TopscorerFragment.newInstance(3));
return list;
}
private class ExamplePagerAdapter extends FragmentPagerAdapter {
String[] pages;
LeagueInfoFragment _activity;
List<Fragment> fragments;
private ExamplePagerAdapter(LeagueInfoFragment a,
FragmentManager fragManager, List<Fragment> frags) {
super(fragManager);
this.fragments = frags;
_activity = a;
pages = new String[] { _activity.getString(R.string.table),
_activity.getString(R.string.fixtures),
_activity.getString(R.string.news),
_activity.getString(R.string.top_scorers) };
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public Fragment getItem(int arg0) {
return fragments.get(arg0);
}
public String getPageTitle(int position) {
return pages[position];
}
}
这是我的片段之一(简化以减少此处发布的代码):
public class NewsFragment extends SherlockFragment implements IAsynchData
{
public static NewsFragment newInstance(int notUsed) {
NewsFragment f = new NewsFragment();
return f;
}
@Override
public View onCreateView(android.view.LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
if (container != null) {
container.removeAllViews();
}
View view = inflater.inflate(R.layout.fragment_news, container,
false);
//Code left out to load the URL in the webview
updateRssFeed("http://www.sportspage.com/myteam");
return view;
}
}