Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 312
wbk727 Avatar asked Apr 10 '26 16:04

wbk727


2 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()); 
}
like image 123
Rohit5k2 Avatar answered Apr 12 '26 05:04

Rohit5k2


In a update these you can now use,

mSlidingTabLayout.setDistributeEvenly(true);

within the onViewCeated,

More can be found here.

like image 28
Jack Avatar answered Apr 12 '26 04:04

Jack