Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabLayout selected tab gravity

TabLayout is set up with ViewPager, has a lot of tabs, MODE_SCROLLABLE and keyline app:tabContentStart="72dp".

When user selects a tab, TabLayout tries to scroll the selected tab to the center. I would like the selected tab to be left aligned to keyline, not centered. Is it possible?

Android Design Support Library v22.2.0.

like image 476
Dima Kornilov Avatar asked Jul 09 '15 17:07

Dima Kornilov


People also ask

What is TabLayout?

com.google.android.material.tabs.TabLayout. TabLayout provides a horizontal layout to display tabs.

How do you use tab items?

The title and icon of Tabs are set through setText(int) and setIcon(int) methods of TabListener interface respectively. Tabs of layout are attached over TabLayout using the method addTab(Tab) method. We can also add tab item to TabLayout using TabItem of android design widget.


2 Answers

Unfortunately the method calculateScrollXForTab() of TabLayout is private and then not replaceable by subclasses. Either way you can copy the source TabLayout in your project, then possibly extending it with your class, and change the method calculateScrollXForTab() like this:

private int calculateScrollXForTab(int position, float positionOffset) {
   if (mMode == MODE_SCROLLABLE) {
      View final selectedChild = mTabStrip.getChildAt(position);
      // LoG.i ("scrollTo" String.valueOf ((int) selectedChild.getLeft()));
      return (int) selectedChild.getLeft();
   }
   return 0;
}

This returns the value of the limit on the left of the tab selected, then scrolling is forced to that value. The extreme right tabs will remain fixed in position if selected because the scroll clamps the scrolling to the bounds of the child.

I tried it and it works, although I had to solve two problems with one CompatTextView not found in android.support.v7.internal.widget and method setupWithViewPager() that does not exist in the source available to me (I think a matter of version)

like image 106
GPack Avatar answered Sep 23 '22 01:09

GPack


If I understood your question well, you can subtract the first tab position from the selected tab position. Then, you just set the different as a position for this selected tab.

like image 20
Lennon Spirlandelli Avatar answered Sep 24 '22 01:09

Lennon Spirlandelli