Android Support Design TabLayout: Gravity Center and Mode Scrollable

前端 未结 13 1989

I am trying to use the new Design TabLayout in my project. I want the layout to adapt to every screen size and orientation, but it can be seen correctly in one orientation.<

13条回答
  •  醉梦人生
    2020-12-02 07:08

    This is the solution I used to automatically change between SCROLLABLE and FIXED+FILL. It is the complete code for the @Fighter42 solution:

    (The code below shows where to put the modification if you've used Google's tabbed activity template)

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    
        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    
        // Set up the tabs
        final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
    
        // Mario Velasco's code
        tabLayout.post(new Runnable()
        {
            @Override
            public void run()
            {
                int tabLayoutWidth = tabLayout.getWidth();
    
                DisplayMetrics metrics = new DisplayMetrics();
                ActivityMain.this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                int deviceWidth = metrics.widthPixels;
    
                if (tabLayoutWidth < deviceWidth)
                {
                    tabLayout.setTabMode(TabLayout.MODE_FIXED);
                    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
                } else
                {
                    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                }
            }
        });
    }
    

    Layout:

        
    

    If you don't need to fill width, better to use @karaokyo solution.

提交回复
热议问题