How To Add Tabbed Activity Into Navigation Drawer Activity?

后端 未结 1 791
攒了一身酷
攒了一身酷 2021-02-03 14:54

I heard that we can not run Android activity inside fragment.

I started a new project with Navigation Drawer Activity chosen. then, I need tabbed activity

1条回答
  •  孤城傲影
    2021-02-03 15:09

    In the navigation drawer activtiy change your layout like this :

    
    
    
    
    
        
        //
        //
        // Tab layout to show tabs
        //
        //
        
    
    
    
    
    
        //
        //
        //ViewPager to show tab's fragments
        //
        //
    
        
        
    
    
        
    
    
    
    
    

    Now in your Activity Java code inside onCreate() add these lines :

        @Override
        protected void onCreate(Bundle savedInstanceState) {
               .
               .
               .
               .
    
        ViewPager vp_pages= (ViewPager) findViewById(R.id.vp_pages);
        PagerAdapter pagerAdapter=new FragmentAdapter(getSupportFragmentManager());
        vp_pages.setAdapter(pagerAdapter);
    
        TabLayout tbl_pages= (TabLayout) findViewById(R.id.tbl_pages);
        tbl_pages.setupWithViewPager(vp_pages);
    
        }
    

    Now outside onCreate() method create the fragment adapter :

    class FragmentAdapter extends FragmentPagerAdapter {
    
        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return new YourFragment1();
                case 1:
                    return new YourFragment2();
                case 2:
                    return new YourFragment3();
            }
            return null;
        }
    
        @Override
        public int getCount() {
            return 3;
        }
    
    
        @Override
        public CharSequence getPageTitle(int position) {
            switch (position){
                //
                //Your tab titles
                //
                case 0:return "Profile";
                case 1:return "Search";
                case 2: return "Contacts";
                default:return null;
            }
        }
    }
    

    Output :

    Cheers, Happy coding.

    0 讨论(0)
提交回复
热议问题