簡體   English   中英

如何在 Tabhost android 中添加圖標和圖像?

[英]how to add icon and Image in Tabhost android?

我正在按照教程使用 Tabhost 添加圖標和文本。

我正在編寫以下代碼以在 tab 中添加文本和圖標。

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
    tabHost.setup();

    TabSpec spec1=tabHost.newTabSpec("Tab 1");
    spec1.setContent(R.id.tab1);
    spec1.setIndicator("Tab 1",getResources().getDrawable(R.drawable.home));

    TabSpec spec2=tabHost.newTabSpec("Tab 2");
    spec1.setContent(R.id.tab2);
    spec2.setIndicator("Tab 2",getResources().getDrawable(R.drawable.home));

    TabSpec spec3=tabHost.newTabSpec("Tab 3");
    spec3.setIndicator("Tab 3",getResources().getDrawable(R.drawable.home));
    spec3.setContent(R.id.tab3);

    tabHost.addTab(spec1);
    tabHost.addTab(spec2);
    tabHost.addTab(spec3);
}

僅在選項卡中添加文本可以正常工作,但會引發以下錯誤消息

java.lang.IllegalArgumentException: you must specify a way to create the tab content at android.widget.TabHost.addTab

在這里需要一些幫助,請...

創建一個選擇器 xml 將其存儲在 drawable 文件夾中並嘗試以下代碼:

TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;

intent = new Intent().setClass(this,YourClass.class);
spec = tabHost.newTabSpec("tab_name").setIndicator("Tab Text", getResources().getDrawable(R.drawable.tab_selector)).setContent(intent);
tabHost.addTab(spec);

用於選擇器的 XML 命名為 tab_selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:state_pressed="false"
        android:drawable="@drawable/ic_tab_selected" />
    <item android:drawable="@drawable/ic_tab_unselected" />
</selector>

ic_tab_selected 和 ic_tab_unselected 這些是將在選擇和取消選擇選項卡時顯示的圖標圖像

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM