TabLayout中的意外边距

时间:2018-04-22 20:07:32

标签: android

我有TabLayout,tabGravity设置为fill

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@drawable/tab_background"
    app:tabGravity="fill"
    app:tabIndicatorHeight="0dp"
    app:tabMaxWidth="0dp"
    app:tabMode="fixed" />

并希望在标签之间添加自定义分隔符。我试过这个方法

View root = tabLayout.getChildAt(0);
LinearLayout linearLayout = (LinearLayout) root;
linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
GradientDrawable drawable = new GradientDrawable();
drawable.setColor(Color.WHITE);
drawable.setSize(5, 0);
linearLayout.setDividerDrawable(drawable);

除了第一个标签的开头,它工作正常。我正在使用SHOW_DIVIDER_MIDDLE,但第一个标签左边有边距:

0 1

如果我删除分隔线,则保证金消失。如何摆脱利润但保留分隔线?

以下是完整的测试项目:https://github.com/PiN73/TestDivider

1 个答案:

答案 0 :(得分:0)

您可以为每个标签扩展不同的布局。

例如:

private void setupTabs() {
    // Left tab inflate
    {
        LinearLayout tab = (LinearLayout) LayoutInflater.from(mContext)
                .inflate(R.layout.tab_left, null);
        TextView tvTabTitle = tab.findViewById(R.id.tvTabTitle);
        tvTabTitle.setText(getResources().getString(R.string.tab_left));
        tabLayout.getTabAt(0)
                .setCustomView(tab);
    }
    // Middle tab inflate
    {
        LinearLayout tab = (LinearLayout) LayoutInflater.from(mContext)
                .inflate(R.layout.tab_middle, null);
        TextView tvTabTitle = tab.findViewById(R.id.tvTabTitle);
        tvTabTitle.setText(getResources().getString(R.string.tab_middle));
        tabLayout.getTabAt(1)
                .setCustomView(tab);
    }

    // Right tab inflate
    {
        LinearLayout tab = (LinearLayout) LayoutInflater.from(mContext)
                .inflate(R.layout.tab_right, null);
        TextView tvTabTitle = tab.findViewById(R.id.tvTabTitle);
        tvTabTitle.setText(getResources().getString(R.string.tab_right));
        tabLayout.getTabAt(2)
                .setCustomView(tab);
    }

}

根据上面的示例,您有3种不同的布局, R.layout.tab_left R.layout.tab_middle R.layout.tab_right

您可以将这些布局排列为:

  • R.layout.tab_left:TextView + Divider
  • R.layout.tab_middle:TextView
  • R.layout.tab_right:Divider + Textview

此外,您可以查看此问题,它是anwswers:How to set the divider between Tabs in TabLayout of design support library?