我要在选项卡周围添加边框,如第二幅图像所示。 我能够如第一幅图所示在顶部和底部添加边框,但不能在每个选项卡的左侧/右侧分别添加边框。
main_activity.xml
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@drawable/tab_border"
android:theme="@style/AppTheme.ActionBar"
android:visibility="invisible"
app:tabIndicatorColor="@color/colorPrimary">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
app:layout_constraintTop_toTopOf="parent" />
@ drawable / tab_border.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#efefef"/>
<stroke android:width="2dp" android:color="#c0c6cc"/>
<corners android:radius="0dp" />
<padding android:left="10dp" android:top="5dp"
android:right="10dp" android:bottom="5dp" />
</shape>
我要在活动类中以编程方式添加选项卡,因为我必须确定运行时的选项卡数。
答案 0 :(得分:1)
使用CustomTabLayout:
public class CustomTabLayout extends TabLayout {
public CustomTabLayout(Context context) {
this(context, null);
}
public CustomTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public void setupWithViewPager(@Nullable ViewPager viewPager) {
super.setupWithViewPager(viewPager);
initCustomTab();
}
@SuppressWarnings({ "ConstantConditions" })
private void initCustomTab() {
int totalTab = getTabCount();
for (int i = 0; i < totalTab; i++) {
Tab tab = getTabAt(i);
if (tab == null) continue;
View view = LayoutInflater.from(getContext())
.inflate(R.layout.item_custom_tab, this, false);
tab.setCustomView(view);
}
}
}
item_custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="@dimen/dp_48"
android:background="@drawable/tab_border"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
希望这会有所帮助