您好我一直试图将一个viewpager放入一个片段中,然而,我已经遵循了许多教程并且无济于事。我试图在另一个片段布局的中间创建一个viewpager,这里是我的代码:
适配器:
public class CardStackAdapter extends FragmentPagerAdapter {
private Context context;
public CardStackAdapter(Context context, FragmentManager fm) {
super(fm);
this.context =context;
}
@Override
public Fragment getItem(int position)
{
return CardStackFragment.newInstance(position);
}
@Override
public int getCount() {
return 5;
}
}
包含ViewPager的片段,包括变换器类:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_social_people,
container, false);
// stack cards
ViewPager mPager;
PagerAdapter mAdapter;
mPager = (ViewPager)view.findViewById(R.id.stackcardvp);
mAdapter = new CardStackAdapter(getActivity(),getChildFragmentManager());
mPager.setPageTransformer(true,new CardStackTransformer());
mPager.setOffscreenPageLimit(2);
mPager.setAdapter(mAdapter);
// mPager.setAdapter(buildAdapter());
return view;
}
变形金刚:
private class CardStackTransformer implements ViewPager.PageTransformer{
@Override
public void transformPage(View page, float position) {
if(position >= 0 ){
page.setScaleX(0.0f-0.02f * position);
page.setScaleY(0.0f);
page.setTranslationX(-page.getWidth()+position);
page.setTranslationY(30 + position);
}
}
}// private class
and viewpager的片段:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_card_stack,
container, false);
return view;
}
public static CardStackFragment newInstance(int selectedIdForIndex) {
CardStackFragment fragment = new CardStackFragment();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_ID, selectedIdForIndex);
fragment.setArguments(args);
return fragment;
}
包含viewpager的片段的XML布局:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="30dp">
<FrameLayout
android:id="@+id/fl"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
>
<android.support.v4.view.ViewPager
android:id="@+id/stackcardvp"
android:layout_width="match_parent"
android:layout_height="320dp"
android:layout_centerInParent="true"
android:visibility="visible" />
</FrameLayout>
</LinearLayout>
问题是当我尝试使用GetChildFragment的不同教程时它仍然没有出现,我甚至尝试创建一个构建适配器但没有结果。 提前感谢您的建议。
答案 0 :(得分:1)
CardStackFragment.newInstance(position)
删除此声明。它会再次重复出现
修改强>:
问题出在这条线上。评论此评论并且您的viewpager应该可以正常工作
mPager.setPageTransformer(true,new CardStackTransformer());
看到你的整个代码后,我发现这个判断错误并将视图放在屏幕外。希望这可以帮到你。
page.setScaleX(0.0f-0.02f * position);