【问题标题】:Customizing TabHost Android自定义 TabHost Android
【发布时间】:2014-02-08 19:46:50
【问题描述】:

我想在标签被选中和取消选中时更改它们的背景图片。我已经从其他问题中遵循了几种方法,但它们似乎没有用,你能检查我的代码,看看我做错了什么吗? (我谈到的问题-How to change the Tabs Images in the TabHost

下面是MainActivity中的标签

TabSpec specs = th.newTabSpec("Tab1");
    specs.setContent(R.id.tab1);
    specs.setIndicator("Tab 1",
            res.getDrawable(R.drawable.tab1_selector));
    th.addTab(specs);

下面是xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use icon1 -->
<item android:drawable="@drawable/selected"
  android:state_selected="true" />
<!-- When not selected, use icon2-->
<item android:drawable="@drawable/unselected"
  android:state_selected="false" />
</selector>

谢谢,汤姆。

【问题讨论】:

    标签: android android-tabhost


    【解决方案1】:

    更新答案..您应该使用此方法 TabSpecs.setIndicator(View view) 并为其提供一个 View 实例(可能是带有 TextView 的 LinearLayout)并将可绘制对象设置为视图的背景。

    创建一个包含 LinearLayout 的新 XML 布局资源,其中一个嵌套的 TextView 作为选项卡的布局。然后您应该创建一个函数,将该 XML 膨胀到 View 实例并设置 TextView 内容(选项卡的标题)。那么你应该用这个视图调用setIndicator() 方法。它会用那个视图有效地替换你的标签的全部内容。

    View v = LayoutInflater.from(this).inflate(R.layout.tab_layout, tabHost.getTabWidget(), false);
    TextView label = (TextView) v.findViewById(R.id.textView);
    label.setText("Title of your tab");
    

    您使用的方法仅将可绘制对象设置为图标(根据文档),所以这可能是问题..

    您也可以通过这种方式设置主题。它应该可以工作。

     <style name="MyCustomTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:tabWidgetStyle">@style/CustomTabWidget</item>
    </style>
    
    <style name="CustomTabWidget" parent="@android:style/Widget.TabWidget">
        <item name="android:background">@drawable/your_drawable</item>
    </style>
    

    或者您可以尝试从您的代码中直接引用选项卡。有点像这样。

    for(int i=0;i<tabHost.getTabWidget().getChildCount();i++) {
        tabHost.getTabWidget().getChildAt(i).setBackground(R.drawable.your_drawable); 
    }
    

    【讨论】:

    • 它使用 tabHost 而不是 actionBar 作为标签。
    • 显然为时过早:) 对此感到抱歉.. 回到办公桌后我会更改答案
    • 对不起,我有点困惑..你能举个例子吗?顺便谢谢你。
    • 所以我把答案扩大了一点:) 你有三种方法都应该起作用..
    • 我之前尝试过第三种方法,但由于某种原因它似乎不起作用,第二种方法有效但看起来像这样 - app.box.com/s/80px01bgd5few5ynsafe 是否可以设置每个标签的图标?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多