Android sliding tabs - set width of tabs programmatically

Question!

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.

SlidingTabLayout.java

protected TextView createDefaultTabView(Context context) {
    TextView textView = new TextView(context);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
    textView.setTypeface(Typeface.DEFAULT_BOLD);
    textView.setTextColor(context.getResources().getColor(R.color.black));
    textView.setWidth(0);

    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



Answers
Add this in your method

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
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) 
{ 
    display.getSize(size); 
} 
else 
{ 
    size.set(display.getWidth(), display.getHeight()); 
}
By : Rohit5k2


In a update these you can now use,

mSlidingTabLayout.setDistributeEvenly(true);

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 SlidingTabLayout.java:

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;

}else{
     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(R.id.stNews);
stNews.setDistributeEvenly(false);
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