简体   繁体   English

Android 更改标签图像(不是背景)

[英]Android change Tab image (not background)

I am using a TabHost which has 3 tabs.我正在使用具有 3 个选项卡的 TabHost。 Each tab has a image + text.每个选项卡都有一个图像 + 文本。

spec = tabHost.newTabSpec("MyTasks")
           .setIndicator(Html.fromHtml("<b><H2>My Tasks</H2></b>"),  getResources().getDrawable(R.drawable.task ))
               .setContent(intent);    
   tabHost.addTab(spec); 

I want to change image when I select a tab.我想在 select 标签时更改图像。 I used following code to change it...我用下面的代码来改变它......

 TabWidget tw = getTabWidget(); 
   View leftTabView = tw.getChildAt(0); 
   leftTabView.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab1_drawable)); 

tab1_drawable is a xml (selector and items for each state). tab1_drawable 是一个 xml(每个状态的选择器和项目)。 THIS IS SETTING AND CHANGING BACKGROUND NOT THE IMAGE I SET.这是设置和更改背景,而不是我设置的图像。 How can I change it?我该如何改变它?

Instead of changing the drawable through code, why not use a state-list drawable ?与其通过代码更改可绘制对象,不如使用状态列表可绘制对象 Then you'd just specify a different drawable for the tab when it is selected.然后,您只需在选项卡被选中时为其指定一个不同的可绘制对象。

Example, ic_tab_tasks.xml:例如,ic_tab_tasks.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_tab_tasks_selected"
          android:state_selected="true" />
    <item android:drawable="@drawable/ic_tab_tasks_normal" />
</selector>

Then, when you're setting the tab indicator's drawable initially, just use the state-list drawable.然后,当您最初设置选项卡指示器的可绘制对象时,只需使用状态列表可绘制对象即可。

try this:试试这个:

  private int index_tab = 0;  
  private TabWidget tabWidget;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.index_layout);    
        TabHost t = (TabHost)findViewById(R.id.testhost);   
        t.setOnTabChangedListener(new OnTabChangeListener() {  
            @Override  
            public void onTabChanged(String tabId) {  
                tabChanged(tabId);  
            }  
        });  
    } 
 public void tabChanged(String tabId) {  
  if (index_tab != (Integer.valueOf(tabId) - 1)) {  
    tabWidget.getChildAt(Integer.valueOf(tabId) - 1)  
      .setBackgroundDrawable(  
       getResources().getDrawable(R.drawable.tab1_drawable));  
       tabWidget.getChildAt(index_tab).setBackgroundDrawable(null);  
        index_tab = Integer.valueOf(tabId) - 1;  
    }  
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM