How to implement a ViewPager with different Fragments / Layouts

前端 未结 6 826
失恋的感觉
失恋的感觉 2020-11-22 00:32

When I start an activity which implements viewpager, the viewpager created various fragments. I want to use different layouts for each fragment, but the problem is that view

6条回答
  •  忘掉有多难
    2020-11-22 00:46

    Code for adding fragment

    public Fragment getItem(int position) {
    
        switch (position){
            case 0:
                return new Fragment1();
    
            case 1:
                return new Fragment2();
    
            case 2:
                return new Fragment3();
    
            case 3:
                return new Fragment4();
    
            default:
                break;
        }
    
        return null;
    }
    

    Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.

    public class Fragment1 extends Fragment {
    
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_one, container, false);
    
            return view;
    
        }
    }
    

    Later you can make necessary corrections.. It worked for me.

提交回复
热议问题