How to Set Background Color TabHost

前端 未结 3 1853
悲&欢浪女
悲&欢浪女 2021-01-13 18:01

I need help, I\'m finding difficulty for change background color in a TabHost.

Original Image:

\"image1\

相关标签:
3条回答
  • 2021-01-13 18:42

    Solution is to use background with selector, and the code is here:

    private void initTabsAppearance(TabWidget tabWidget) {
        // Change background
        for(int i=0; i < tabWidget.getChildCount(); i++)
            tabWidget.getChildAt(i).setBackgroundResource(R.drawable.tab_bg);
    }
    

    Where tab_bg is an xml drawable with selector:


    For the full Tab customization I will add the code for changing tab text style using custom theme. Add this to styles.xml:

    <style name="MyCustomTheme" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="android:tabWidgetStyle">@style/CustomTabWidget</item>
    </style>
    
    <style name="CustomTabWidget" parent="@android:style/Widget.TabWidget">
        <item name="android:textAppearance">@style/CustomTabWidgetText</item>
    </style>
    
    <style name="CustomTabWidgetText" parent="@android:style/TextAppearance.Widget.TabWidget">
        <item name="android:textSize">12sp</item>
        <item name="android:textStyle">bold</item>
    </style>
    

    To use this theme, define it in AndroidManifest.xml:

    <application android:theme="@style/MyCustomTheme">
    

    And now you have tab widgets with custom background and custom text style.

    0 讨论(0)
  • 2021-01-13 18:59

    I am solved exactly the same problem with this method:

    private void setBackgroundColor() {
        int inactiveColor = getResources().getColor(R.color.inactive_tab);
        int activeColor = getResources().getColor(R.color.active_tab);
    
        // In this loop you will set the inactive tabs backgroung color
        for (int i = 0; i < tabWidget.getChildCount(); i++) {
            tabWidget.getChildAt(i).setBackgroundColor(inactiveColor);
        }
    
        // Here you will set the active tab background color
        tabWidget.getChildAt(tabHost.getCurrentTab()).setBackgroundColor(
                activeColor);
    }
    
    0 讨论(0)
  • 2021-01-13 19:07
    tabHost.setOnTabChangedListener(new OnTabChangeListener() {
    
            public void onTabChanged(String arg0) {
                for (int i = 0; i < tab.getTabWidget().getChildCount(); i++) {
                    tab.getTabWidget().getChildAt(i)
                            .setBackgroundResource(R.drawable.tab_selected); // unselected
                }
                tab.getTabWidget().getChildAt(tab.getCurrentTab())
                        .setBackgroundResource(R.drawable.tab_unselected); // selected
    
            }
        });
    

    Try this method, I hope this will help you.

    0 讨论(0)
提交回复
热议问题