我打算創建具有輕掃手勢的產品之間切換的應用程序。起初,我使用導航抽屜創建應用程序。這個抽屜項目/菜單將加載不同的片段。如何從數據庫加載ViewPager片段中的數據dinnamicaly
在這個特定的片段中,名爲coupon,我想實現viewpager。這就是我實現我的嘗試:
創造出加載優惠券片段當我點擊導航抽屜項目之一
上CouponFragment.java我把:
mCustomPagerAdapter = new CustomPagerAdapter(getFragmentManager(), getActivity()); mViewPager = (ViewPager) view.findViewById(R.id.pager); mViewPager.setAdapter(mCustomPagerAdapter);
on fragment_coupon.xml我把ViewPager
我創建CustomPagerAdapter擴展FragmentPagerAdapter:
公共類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 [email protected] 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條記錄,對吧? – Gabriel
獲得所有20個產品一次構成數據庫並傳遞CustomPagerAdapter(列表列表,...)內的列表;並在getCount()return list.size –