How to set Tab Image when using FragmentTabHost?

6.9k Views Asked by At

I wrote app of Tab Navigation using android.support.v4.app.FragmentTabHost. I want to add image background to my Tabs. Code is here:

  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab);
    instance = this;


    history = new HashMap<String, Stack<Fragment>>();
    tabhost = (FragmentTabHost)findViewById(android.R.id.tabhost);

    tabhost = (FragmentTabHost)findViewById(android.R.id.tabhost);
    tabhost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

    TabSpec tab1 = tabhost.newTabSpec("0").setIndicator("Home");
    TabSpec tab2 = tabhost.newTabSpec("1").setIndicator("Sign Up");
    TabSpec tab3 = tabhost.newTabSpec("2").setIndicator("Tab3");



    System.out.print("second out");




    tabhost.addTab(tab1, myFragment.class, null);
    tabhost.addTab(tab2, myFragment2.class, null);
    tabhost.addTab(tab3, myFragment3.class, null);
1

There are 1 best solutions below

5
On

You can add drawables from the resources to the TabSpec. This is how:

Resources res = getResources(); // Resource object to get Drawables  
TabHost tabHost = getTabHost();  
TabHost.TabSpec spec;  // Resusable TabSpec for each tab

// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("1").setIndicator(res.getString(R.string.tabname1), 
                                            res.getDrawable(R.drawable.tabimage1));
tabHost.addTab(spec, FragmentOne.class, null);

spec = tabHost.newTabSpec("2").setIndicator(res.getString(R.string.tabname2), 
                                            res.getDrawable(R.drawable.tabimage2));
tabHost.addTab(spec, FragmentTwo.class, null);

spec = tabHost.newTabSpec("3").setIndicator(res.getString(R.string.tabname3), 
                                            res.getDrawable(R.drawable.tabimage3));
tabHost.addTab(spec, FragmentThree.class, null);

//... and so on ...

See here for the full tutorial:

http://maxalley.wordpress.com/2013/05/18/android-creating-a-tab-layout-with-fragmenttabhost-and-fragments/