选项卡添加动态时,未设置宽度以匹配父级

时间:2016-10-17 14:17:59

标签: android android-layout

如果tab为4,我动态添加了tab,那么它显示效果很好但是如果tab是2或3那么它不是与父级匹配的脚。

代码

 public void setUpTab(TabLayout tabLayout, String count, String typeId) {

    TabLayout.Tab tab = tabLayout.newTab();

    RelativeLayout relativeLayout = (RelativeLayout)
            LayoutInflater.from(this).inflate(R.layout.custom_tab, tabLayout, false);
    TextView tabTextView = (TextView) relativeLayout.findViewById(R.id.txt_tab);
    tabTextView.setText(count);
    tab.setTag(typeId);
    tab.setCustomView(tabTextView);
    tabLayout.addTab(tab);
}

Xml代码:

 <android.support.design.widget.TabLayout
    android:id="@+id/tabsRoleType"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/com_facebook_likeboxcountview_border_radius"
    app:tabBackground="@drawable/tab_rounded_background"
    app:tabGravity="fill"
    app:tabIndicatorHeight="0dp"
    app:tabSelectedTextColor="@color/WhiteColor"
    app:tabTextAppearance="@style/TextAppearance.Design.Tab"
    app:tabTextColor="@color/BlackColor" />

enter image description here

2 个答案:

答案 0 :(得分:1)

在XML TabLayout

中添加/更新以下行
<android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMaxWidth="0dp"
        app:tabGravity="fill"
        app:tabMode="fixed" />

良好做法是app:tabMode="scrollable"

答案 1 :(得分:1)

添加android:tabMaxWidthandroid:tabModeandroid:tabgravity

示例XML代码:

 <android.support.design.widget.TabLayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:tabIndicatorColor="@color/colorPrimary"
    app:tabIndicatorHeight="3dp"
    app:tabMaxWidth="0dp"
    app:tabGravity="fill"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorPrimary"
    app:tabTextAppearance="@style/TabLayoutTextStyle"
    app:tabTextColor="@color/textCol" />