Can I use view pager with views (not with fragments)

前端 未结 7 2008
情深已故
情深已故 2020-11-28 01:39

I am using ViewPager for swiping between Fragments, but can I use ViewPager to swipe between Views simple XML layout?

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 02:21

    I would like to add my solution here. Given that you don't need to use fragments, you can still create a PagerAdapter which attaches views instead of fragments to the ViewPager.

    Extend PagerAdapter instead of FragmentPagerAdapter

    public class CustomPagerAdapter extends PagerAdapter {
    
      private Context context;
    
      public CustomPagerAdapter(Context context) {
        super();
        this.context = context;
      }
    
    
      @Override
      public Object instantiateItem(ViewGroup collection, int position) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = null;
        switch (position){
          case 0:
            view = MemoryView.getView(context, collection);
            break;
          case 1:
            view = NetworkView.getView(context, collection);
            break;
          case 2:
            view = CpuView.getView(context, collection);
            break;
        }
    
        collection.addView(view);
        return view;
      }
    
      @Override
      public int getCount() {
        return 3;
      }
    
      @Override
      public boolean isViewFromObject(View view, Object object) {
        return view==object;
      }
    
      @Override
      public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
      }
    }
    

    Now you need to define three classes which will return the views to be inflated in the viewpager. Similar to CpuView you will have MemoryView and NetworkView classes. Each of them will inflate their respective layouts.

    public class CpuView {
    
    public static View getView(Context context, ViewGroup collection) {
    
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context
            .LAYOUT_INFLATER_SERVICE);
        return inflater.inflate(R.layout.debugger_cpu_layout, collection, false);
      }
    }
    

    And finally a layout which will be inflated in each of the views

        
    
    
        
    
    

    P.S.: The reason I wrote this answer is because all the solutions provided here seems to be working fine, but they are inflating the layouts in the PagerAdapter class itself. For large projects it becomes difficult to maintain if their is a lot of code related to the layouts inflated. Now in this example all the views have separate classes and separate layouts. So the project can be easily maintained.

提交回复
热议问题