Pat Needham
Pat Needham

Reputation: 5638

Using tabs in Android

I made a password generator app that works well, but I want to update it so it can save passwords. I want to have one tab where the user sees the generated passwords and has the option to save one of them, and another tab with the saved passwords. I looked at the developer.android.com tutorials, but I don't like how you have to make a separate activity for each tab. I've used tabs to create WPF applications using XAML and C#, where I just have to use the TabControl and TabItem in the XAML code. Is it possible to do something similar to this?

Upvotes: 0

Views: 485

Answers (1)

Joishi Bodio
Joishi Bodio

Reputation: 438

You don't have to create a separate activity for each tab.. You do, however, have to have a layout for each tab. You need a TabHost, a TabWidget, and a FrameLayout. The TabWidget and FrameLayout have to be children of the TabHost, and they also have to have specific ID's assigned to them. The TabWidget has to have the ID of android.R.id.tabs. The FrameLayout has to have the ID of android.R.id.tabcontent. Any Views or Layouts you want to be displayed (for any part of the TabHost) have to be added to the FrameLayout. THEN you need to create a TabSpec that links everything together. It looks sorta like this (progmatically)..

TabHost host = new TabHost(context);
TabWidget widget = new TabWidget(context);
widget.setID(android.R.id.tabs);
FrameLayout frame = new FrameLayout(context);
frame.setID(android.R.id.tabcontent);
frame.addView(viewForTab1);
frame.addView(viewForTab2);
host.addView(widget);
host.addView(frame);
host.setup();  //must be called when defining a tabhost outside of a tabactivity, iirc..
TabSpec spec;
do {
    spec = host.newTabSpec(uniqueStringReference);
    spec.setContent(viewOrLayoutForTheTab);
    spec.otherStuffYouMightWant();
    host.addTab(spec);
} while (you have tabs to add);

Upvotes: 1

Related Questions