【发布时间】:2013-04-03 17:44:31
【问题描述】:
我有一个布局,其中包含 2 个彼此相邻的片段。在每个片段中,我都有一个 ViewPager。由于我需要两个 Fragment 看起来相同,因此我对两者使用相同的布局 XML,其中包含一个 ViewPager。
现在当我测试应用程序时,似乎只有第一个 Fragment 的 ViewPager 可以工作。第二个 Fragment 显示一个 PagerTitleStrip,我可以翻阅它,但它没有显示 ViewPager 中的 Fragments。
为什么第二个 ViewPager 也没有显示片段?这是什么原因造成的? 问题是他们使用相同的布局吗?反正它不是一个不同的对象吗?
Activity中2个Fragment共享的布局如下:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTitleStrip
android:id="@+id/search_mapping_pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
两个 Fragment 都以相同的方式实例化 ViewPager:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search_mapping,
container, false);
mSectionsPagerAdapter = new SectionsPagerAdapter(mActivity
.getSupportFragmentManager());
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
return view;
}
编辑:更多代码显示我的SectionsPagerAdapter:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = new SuperclassFragment();
Bundle args = new Bundle();
args.putInt(SuperclassFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
...
}
我应该在哪里寻找错误原因的任何提示?如果需要,我当然可以在此处包含更多代码。
【问题讨论】:
-
你应该把 Viw=ewPage 放在线性/相对布局下。另外,你能不能把 SectionsPagerAdapter 的代码放上去,因为 getItem 函数很有趣
-
我认为使用线性/相对布局是对的。我已经放了 SectionsPagerAdapter 的代码。可能是问题在于他们使用相同的
FragmentManager实例? -
我认为,行 Fragment fragment = new SuperclassFragment();是问题。 View Paget 会调用 getItem 方法,此时,你返回的是 SuperclassFragment。它是一个父类,因此 View Pager 不知道要渲染哪个片段,它会使用它在类路径中找到的第一个片段,但我不确定
-
不,如果你是这个意思,它不是抽象类。这个名字有点误导,但它只是一个普通的
public static class SuperclassFragment extends Fragment,它与使用 ADT Eclipse 的 Activity 向导生成 ViewPager 导航时得到的DummySectionFragment基本相同。
标签: android android-fragments android-viewpager android-xml