Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different tab width for TabLayout

I'm using TabLayout & ViewPager. I am trying to change the size of the Tab, like Whatsapp (camera icon). The size of the three Tabs is equal, but the Tab of the camera is smaller. In every attempt I make the size of the Tabs remains the same (equal across all tabs). Thanks.

enter image description here

like image 763
Dor Natan Avatar asked Apr 30 '17 17:04

Dor Natan


People also ask

Can we use TabLayout without ViewPager in Android?

It is possible to use a TabLayout without a ViewPager by using a TabLayout. OnTabSelectedListener . For navigation within an Activity , manually populate the UI based on the tab selected.


2 Answers

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!

like image 139
digger Avatar answered Sep 24 '22 11:09

digger


@digger's answer is working. However, if you want the tab which has an icon only wraps its content, you can set weight to 0 and width to LinearLayout.LayoutParams.WRAP_CONTENT. It worked for me.

fun TabLayout.setTabWidthAsWrapContent(tabPosition: Int) {
    val layout = (this.getChildAt(0) as LinearLayout).getChildAt(tabPosition) as LinearLayout
    val layoutParams = layout.layoutParams as LinearLayout.LayoutParams
    layoutParams.weight = 0f
    layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT
    layout.layoutParams = layoutParams
}
like image 32
sembozdemir Avatar answered Sep 22 '22 11:09

sembozdemir