【发布时间】:2017-05-16 08:18:13
【问题描述】:
我的目标是创建具有滑动手势以在产品之间切换的应用程序。首先,我创建带有导航抽屉的应用程序。这个抽屉项目/菜单将加载不同的片段。
在这个名为 coupon 的特定片段中,我想实现 viewpager。这是我在尝试中取得的成果:
创建当我单击导航抽屉中的一项时加载的优惠券片段
-
在我放的 CouponFragment.java 上:
mCustomPagerAdapter = new CustomPagerAdapter(getFragmentManager(), getActivity()); mViewPager = (ViewPager) view.findViewById(R.id.pager); mViewPager.setAdapter(mCustomPagerAdapter); 在 fragment_coupon.xml 上我放了 ViewPager
-
我创建了扩展 FragmentPagerAdapter 的 CustomPagerAdapter:
公共类 CustomPagerAdapter 扩展 FragmentPagerAdapter {
protected Context mContext; public CustomPagerAdapter(FragmentManager fm, Context context) { super(fm); mContext = context; } @Override // This method returns the fragment associated with // the specified position. // // It is called when the Adapter needs a fragment // and it does not exists. public Fragment getItem(int position) { // Create fragment object Fragment fragment = new DemoFragment(); // Attach some data to it that we'll // use to populate our fragment layouts Bundle args = new Bundle(); args.putInt("page_position", position + 1); args.putString("coupon_name", "Promo Lorem Ipsum"); args.putString("coupon_desc", "description is here"); // Set the arguments on the fragment // that will be fetched in DemoFragment@onCreateView fragment.setArguments(args); return fragment; } @Override public int getCount() { return 3; }}
-
我创建了加载在适配器内部的 DemoFragment.java:
公共类 DemoFragment 扩展片段 {
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout resource that'll be returned View rootView = inflater.inflate(R.layout.fragment_demo, container, false); // Get the arguments that was supplied when // the fragment was instantiated in the // CustomPagerAdapter Bundle args = getArguments(); ((TextView) rootView.findViewById(R.id.text)).setText("Page " + args.getInt("page_position")); ((TextView) rootView.findViewById(R.id.test1)).setText("" + args.getString("coupon_name")); ((TextView) rootView.findViewById(R.id.test2)).setText("" + args.getString("coupon_desc")); return rootView; }}
-
我创建 fragment_demo.xml:
<TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Page 0" android:id="@+id/text" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/test1"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/test2"/>
我的问题:
- 我想在那里加载一堆产品,比如说 20 个产品要刷卡。我怎样才能做到这一点?我只有位置,但没有加载数据的产品 ID
【问题讨论】:
-
您希望加载产品数据的依据是什么,即据我了解,从数据库中获取这 20 个产品并将其传递给适配器??
-
@VikasRathod 我可以使用什么功能?在 getItem 上,我一次只加载 1 条记录,对吧?
-
从数据库中获取所有 20 个产品并在 CustomPagerAdapter(List
list,...) 中传递一个列表;并在 getCount() 返回 list.size -
不确定我是否理解它的工作原理,但我会先尝试一下。谢谢!
-
@VikasRathod 它的作品!谢谢!