Android sliding tabs - set width of tabs programmatically


With my sliding tabs project, how can I programmatically set the width of the tabs so that they use the whole space of the sliding tab strip and are each equal in width size? I've tried using the code below but the tabs won't stretch as desired.

protected TextView createDefaultTabView(Context context) {
    TextView textView = new TextView(context);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);

    int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
    textView.setPadding(padding, padding, padding, padding);

    return textView;

enter image description here

Text weight error

text weight error

Add this in your method

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
textView.setWidth(size.x / count); // Where count is number of textviews

Also if you are supporting older version

Use this

if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) 
    size.set(display.getWidth(), display.getHeight()); 
By : Rohit5k2

In a update these you can now use,


within the onViewCeated,

More can be found here.

By : jackdh

I have a different problem, wherein I had to customize each of the tabs' width:

Distribute Evenly

I was using setDistributeEvenly function. Instead I needed to set each of the textviews' weight.

Add this variable on your

private int[] mTabWeights;

This method should set the tab weights:

public void setTabWeights(int[] weights){
        mTabWeights = weights;

Look for the method populateTabStrip() and add an else statement:

if (mDistributeEvenly) {
     LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
     lp.width = 0;
     lp.weight = 1;

     LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
     lp.width = 0;
     lp.weight = mTabWeights[i];

You can refactor the code to make it cleaner. Here it is when used:

stNews = (SlidingTabLayout) findViewById(;
stNews.setTabWeights(new int[]{2,3,3});

Here's the end result:

enter image description here

Hope it helps!

This video can help you solving your question :)
By: admin