Search code examples
javaandroidandroid-actionbarandroid-tabhost

Change ActionBar tab color programmatically


I have the following ActionBar tab in my app. I was wondering what is the best way to change the colors around to match my app.

enter image description here

  1. Each tab has a different background for the contents. How do I add separate background colors for each tab?
  2. How do I change the light blue strip color to white to give it a 3D look?

I saw the following code:

ActionBar ab = getActionBar();
//ab.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));

But that line changes color for all the tabs to just one color.

The Tab code in my app is:

ActionBar ab = getActionBar();
        //ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff"))); not changing the tab color
        //ab.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));
        ab.setNavigationMode( ActionBar.NAVIGATION_MODE_TABS );

        Tab tab = ab.newTab()
                .setText( "TY1" )
                .setTabListener( 
                        new MyTabListener( this, TY1.class.getName() ) );
        ab.addTab( tab );

        tab = ab.newTab()
                .setText( "TY2" )
                .setTabListener( 
                        new MyTabListener( this, TY2.class.getName() ) );
        ab.addTab( tab );

        tab = ab.newTab()
                .setText( "ty3" )
                .setTabListener( 
                        new MyTabListener( this, TY3.class.getName() ) );
        ab.addTab( tab );

Any and all help is appreciated. I can use XML as well, if someone points me in the right direction.


Solution

  • You can set a custom View for each tab. Create a new layout resource for the tab (it can just be a TextView). Leave its background empty and make a nine-patch drawable for the selection indicator. Get a LayoutInflater using

    LayoutInflater inflater = getSystemService(LAYOUT_INFLATER_SERVICE);
    

    Then for each tab, you can do this:

    Tab tab = ab.newTab()
            .setText("TY1")
            .setTabListener(new MyTabListener(this, TY1.class.getName()));
    View tabView = inflater.inflate(R.layout.my_tab_layout, null);
    tabView.setBackgroundColor(...); // set custom color
    tab.setCustomView(tabView);
    ab.addTab(tab);