John
John

Reputation: 105

How to change width of a single tab in a ViewPager android?

I would like the first tab to be 24dp and two other to fill the left space evenly. How do I do this?

MainActivity.java

viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setCustomView(R.layout.custom_tab);

custom_tab.xml

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/tab"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:gravity="center_horizontal"
          android:src="@drawable/ic_settings_black_24dp"/>

Even if I set the layout_width in custom_tab to 24 dp, nothing changes.

Upvotes: 2

Views: 886

Answers (2)

John
John

Reputation: 105

Ok, so I was browsing the internet looking for the correct answer, I checked the medium source sent by @mmuccito but I didn't find the solution there. Then I noticed the similar stackoverflow question which has the answer to this problem submitted by @digger:

You need to lower the weight of the LinearLayout of the corresponding tab.

LinearLayout layout = ((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(YOUR_TAB_NUMBER));
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams();
layoutParams.weight = YOUR_WEIGHT; // e.g. 0.5f
layout.setLayoutParams(layoutParams);

Hope that helps!

Upvotes: 1

mmucito
mmucito

Reputation: 134

You will neeed a custom TabLayout. here is an example that can help you. https://medium.com/@elsenovraditya/set-tab-minimum-width-of-scrollable-tablayout-programmatically-8146d6101efe

Upvotes: 1

Related Questions