Here's another approach: to separate the header from the tabs. A bit complicated, yes, but the benefits are:
- It allows you to define common tabs style;
- Supports any number of buttons.
On this picture the buttons are of different width, so in reality an additional ImageView
may be needed to the left of the header.
Let's create our header view as a LinearLayout. We can put upper dividers and stretchable gaps with the same layout_weight
.
public class HeaderLayout extends LinearLayout {
public HeaderLayout(Context context) {
super(context);
initView();
}
public HeaderLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public void setNumberOfColumns(int number) {
removeAllViews();
for (int i = 0; i < number; i++) {
addView(getColumnView(), getColumnLayoutParams());
// We don't need a divider after the last item
if (i < number - 1) {
addView(getDividerView(), getDividerLayoutParams());
}
}
}
private void initView() {
setBackgroundResource(R.drawable.header_bg);
}
private View getColumnView() {
return new View(getContext());
}
private View getDividerView() {
ImageView dividerView = new ImageView(getContext());
dividerView.setImageResource(R.drawable.header_divider);
dividerView.setScaleType(ImageView.ScaleType.FIT_XY);
return dividerView;
}
private LayoutParams getColumnLayoutParams() {
return new LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);
}
private LayoutParams getDividerLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
}
}
Where R.drawable.header_bg
is a 9patch:
And R.drawable.header_divider
is a simple (optionally transparent) bitmap:
For me personally, making different background for the first and the last button is the least difficult solution, but it depends on the actual task.