Android Tabs in middle of layout

后端 未结 2 1748
无人共我
无人共我 2021-01-14 03:39

In the middle of my layout I want to have 2 tabs to choose between viewing 2 different lists in the second half of the screen. How can I do this?

Here is an image il

2条回答
  •  不思量自难忘°
    2021-01-14 04:06

    I had to do the same today! I tried with PagerTabStrip, because I thought you can't use TabLayout if it's not with a Toolbar. Turns out I was wrong, and it's even used in Google iosched. So you can put a TabLayout + ViewPager wherever you want.

    I know you want to do some very custom tabs, which would be easier to customize if they were buttons, but in my opinion it's better to use TabLayout + ViewPager, since it makes things more scalable.

    activity_main.xml

    
    
    
        
    
        
    
            
    
            
        
    
    
    

    MainActivity class:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Locate the viewpager in activity_main.xml
            ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    
            // Set the ViewPagerAdapter into ViewPager
            ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
            adapter.addFrag(new LeftFragment(), "Players");
            adapter.addFrag(new RightFragment(), "Prizes");
    
            viewPager.setAdapter(adapter);
    
            TabLayout mTabLayout = (TabLayout) findViewById(R.id.pager_header);
            mTabLayout.setupWithViewPager(viewPager);
        }
    
        class ViewPagerAdapter extends FragmentStatePagerAdapter {
            private final List mFragmentList = new ArrayList<>();
            private final List mFragmentTitleList = new ArrayList<>();
    
            public ViewPagerAdapter(FragmentManager manager) {
                super(manager);
            }
    
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }
    
            @Override
            public int getCount() {
                return mFragmentList.size();
            }
    
            public void addFrag(Fragment fragment, String title) {
                mFragmentList.add(fragment);
                mFragmentTitleList.add(title);
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                return mFragmentTitleList.get(position);
            }
        }
    }
    

    You can change the adapter you use, it doesn't matter.

    To customize tabs, I'd take a look at this amazing tutorial.

提交回复
热议问题