简体   繁体   中英

PagerAdapter using fragments

Below is an example of a PagerAdapter. Is it possible to get fragments and add these to the container instead of writing all logic in instantiateItem ?

Thanks in advance

@Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view=null;
            if(position%2==0){
                view = activity.getLayoutInflater().inflate(R.layout.pager_item,container, false);
            }else{
                view = activity.getLayoutInflater().inflate(R.layout.pager_item,container, false);
            }
            // Add the newly created View to the ViewPager
            container.addView(view);

            // Retrieve a TextView from the inflated View, and update it's text
            TextView title = (TextView) view.findViewById(R.id.item_title);
            title.setText(tabs[position]);

            // Return the View
            return view;
        }

Use either FragmentPagerAdapter (for low amount of pages which will be kept in memory) or FragmentStatePagerAdapter (for high amount of pages which will be saved if too far from current screen). You need only override getCount() and getItem(int position) which is supposed to return a new fragment instance based on position.

Docs as well as usage examples: http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM