简体   繁体   中英

Trouble with Android TabHost

I want to creat my tab host programmaticly, as it seems I can't add icons otherwise? Anyways... This is how I do it. I get an error when trying to use the tabHost.addTab() function.

private void setupTabs() {
    Log.d("DEBUG", "Starting tab setup");
    createTab("Hjem", R.drawable.ic_menu_home, HomeActivity.class);
    createTab("Nyheter", R.drawable.ic_menu_home, HomeActivity.class);
    createTab("Podcast", R.drawable.ic_menu_home, HomeActivity.class);
    Log.d("DEBUG", "Finished tab setup");
}

private void createTab(String label, int drawableId, Class<?> activity) {
    //Create tab
    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
    TabSpec spec = tabHost.newTabSpec("tab" + label);

    //Set indicator
    Drawable image = ContextCompat.getDrawable(this, drawableId);
    spec.setIndicator(label, image);

    //Set content
    Intent intent = new Intent(this, activity);
    spec.setContent(intent);

    //Add tab
    tabHost.addTab(spec);
}

I did some more searches and managed to figure it out. I primarily did 3 changes.

  1. Change the id of my designer tab to @android:id/tabhost
  2. Change the activity to extends TabActivity
  3. Add tabHost.setup() after grabbing the refrence to tabHost

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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