簡體   English   中英

Android 更改標簽圖像(不是背景)

[英]Android change Tab image (not background)

我正在使用具有 3 個選項卡的 TabHost。 每個選項卡都有一個圖像 + 文本。

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

我想在 select 標簽時更改圖像。 我用下面的代碼來改變它......

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

tab1_drawable 是一個 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>

然后,當您最初設置選項卡指示器的可繪制對象時,只需使用狀態列表可繪制對象即可。

試試這個:

  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