Icon in Tab is not showing up

后端 未结 4 850
情书的邮戳
情书的邮戳 2020-11-27 14:03

I\'m starting with Android and when I try to do a TabHost with an icon and a text. Only the text is visible, if I left the text in blank it is possible to see the icon. I wa

4条回答
  •  情深已故
    2020-11-27 14:13

    This is a easy way to show the text and icon in ICS. After to setup the Tabhost, I call the next methods:

    setTabIcon(mTabHost, 0, R.drawable.ic_tab1); //for Tab 1
    setTabIcon(mTabHost, 1, R.drawable.ic_tab2); //for Tab 2
    
    public void setTabIcon(TabHost tabHost, int tabIndex, int iconResource) {
        ImageView tabImageView = (ImageView) tabHost.getTabWidget().getChildTabViewAt(tabIndex).findViewById(android.R.id.icon);
        tabImageView.setVisibility(View.VISIBLE);
        tabImageView.setImageResource(iconResource);
    }
    

    If you want a more advanced solution, you need to create a layout like @sunadorer recommend. My recommendation is that you can create your layout using the holo theme layout, search the file on your sdk_dir/platforms/android-14/data/res/layout/tab_indicator_holo.xml.

    My advanced solution is the next, you need to create a layout like this:

    tab_indicator.xml

    
    
    
        
    
        
    
    
    

    In your activity or fragment, create the next function:

    public View createTabIndicator(LayoutInflater inflater, TabHost tabHost, int textResource, int iconResource) {
        View tabIndicator = inflater.inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
        ((TextView) tabIndicator.findViewById(android.R.id.title)).setText(textResource);
        ((ImageView) tabIndicator.findViewById(android.R.id.icon)).setImageResource(iconResource);
        return tabIndicator;
    }
    

    And finally when you create your tab in your activity or fragment use the next code:

    mTabHost.addTab(
        mTabHost.newTabSpec("tab1")
        .setIndicator(createTabIndicator(inflater, mTabHost, R.string.tab1, R.drawable.ic_tab1))
        .setContent(R.id.tab1)
    );
    

    I have tested this solution in ICS and works fine.

    Good luck :)

提交回复
热议问题