I want to create an Android tab view to look like this image:
I guess there are many ways to Rome, but I think I still haven't found the ideal one. My idea was to cut out a divider and an active divider and place them between the buttons. However, I don't know if this would be such a good solution because I still would need different styling for the first and last button. I already have a 9 patch for the surrounding (grey) container.
I've also thought about making a red 9 patch for the red bar, and than just style the selected button. The problem with this solution is that I'd still have to place the top diagonal white lines according to the number of buttons.
Does anyone have a better solution for me?
Here's another approach: to separate the header from the tabs. A bit complicated, yes, but the benefits are:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With