我该如何在Android中更改TabWidget分隔线的颜色和/或可绘制对象?

5

我正在使用TabLayout,我有自定义图像用于选项卡,但是我无法弄清楚如何更改选项卡和选项卡内容之间分隔符的颜色或甚至图像。我尝试使用setDividerDrawable(),但在设置选项卡内容之前调用它会导致崩溃,并且在之后调用它时什么也不做。如果我可以让它变成黑色就足够了,但到目前为止没有任何作用。感谢您的任何指导。

2个回答

9
您需要这样做: tabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
其中 R.drawable.tab_divider 是您资源目录中的图像。 但关键是,在将任何选项卡添加到选项卡主机之前,您必须这样做。 我的选项卡初始化代码如下:
private void initializeTabs(int curTab) {
    this.tabHost = getTabHost();
    tabHost.clearAllTabs();

    TabSpec ts1, ts2, ts3, ts4, ts5;
    // tab separator
    tabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);

    ts1 = this.setupTab(new TextView(this), tabHost, R.drawable.browse_tab_normal, 
            mResources.getString(R.string.Browse));

    ts2 = this.setupTab(new TextView(this), tabHost, R.drawable.search_tab_normal, 
            mResources.getString(R.string.Search));

    ts3 = this.setupTab(new TextView(this), tabHost, R.drawable.postad_tab_normal, 
            mResources.getString(R.string.Post));

    ts4 = this.setupTab(new TextView(this), tabHost, R.drawable.watchlist_tab_normal, 
            mResources.getString(R.string.WatchList));

    ts5 = this.setupTab(new TextView(this), tabHost, R.drawable.managead_tab_normal, 
            mResources.getString(R.string.Login));

    // intents
    ts1.setContent(new Intent().setClass(this, BrowseTabActivity.class));
    ts2.setContent(new Intent().setClass(this, SearchTabActivity.class));
    ts3.setContent(new Intent().setClass(this, PostAdTabActivity.class));
    ts4.setContent(new Intent().setClass(this, WatchlistTabActivity.class));
    ts5.setContent(new Intent().setClass(this, LoginTabActivity.class));

    tabHost.addTab(ts1);
    tabHost.addTab(ts2);
    tabHost.addTab(ts3);
    tabHost.addTab(ts4);
    tabHost.addTab(ts5);

...


答案是可以的,但我如何使用相同的代码设置颜色而不是图像呢?谢谢! - benoffi7

0

定义分隔符的更好方式是从您的XML标记中创建它:

<TabWidget
     android:layout_width="match_parent"
     android:showDividers="middle"
     android:divider="@drawable/design_tab_divider">
 </TabWidget>

所以,您可以仅从标记定义可绘制对象。 请注意,您必须使用android:dividerandroid:showDividers="middle"来在选项卡之间放置分隔符。 要了解更多信息,请阅读规范并注意从LinearLayout继承的属性 - 谷歌文档

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接