Android TabLayout with active tab always at center

2019-06-23 14:56发布

问题:

In android.support.design.widget.TabLayout, how to make the active tab always appear at the center, just like in Play Newsstand app, as shown below.

The first and last tab should also appear at the center.

I tried using padding on the TabLayout. It is not working. This is the code that I wrote:

<android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="@color/yellow"
            app:tabSelectedTextColor="@android:color/white"
            app:tabTextColor="#EEE"
            app:tabMode="scrollable"
            android:gravity="bottom"
            android:clipToPadding="false"
            android:paddingLeft="90dp"
            android:paddingRight="90dp"
            />

In this case, the tabIndicator will also shift 90dp from left. It should remain at the center independent of the padding.

回答1:

Checkout this solution: https://stackoverflow.com/a/36886331/651770

Could be solved by tabContentStart, but if you want to center both sides of Tablayout, you need to extend this class and set the padding by hand.



回答2:

Maybe a little late, but you can try using this library :

https://github.com/jpardogo/PagerSlidingTabStrip

This can be done as they said :

Include the following dependency in your build.gradle file.

compile 'com.jpardogo.materialtabstrip:library:1.1.1'

Or add the library as a project. I tried to send a pull request, but looks like the original developer doesn't maintain it anymore.

Include the PagerSlidingTabStrip widget in your layout. This should usually be placed above the ViewPager it represents.

<com.astuetz.PagerSlidingTabStrip
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary" />

In your onCreate method (or onCreateView for a fragment), bind the widget to the ViewPager:

// Initialize the ViewPager and set an adapter
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new TestAdapter(getSupportFragmentManager()));

// Bind the tabs to the ViewPager
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);

Hope this help.