Java – Android Sliding Label – Programmatically sets the width of the label

Android Sliding Label – Programmatically sets the width of the label… here is a solution to the problem.

Android Sliding Label – Programmatically sets the width of the label

For my slide label project, how do I programmatically set the width of the labels so that they use the entire space of the slide label strip and the width size of each label is equal? I’ve tried using the code below, but the tabs won’t stretch as needed.

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

Solution

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 support older versions

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()); 
}

Related Problems and Solutions