Switch between Android tabs using intents
I wish to find out how to switch between tabs using intents.
In my case I'm using the both tabs:
Resources res = getResources();
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
// Capture tab
spec = tabHost.newTabSpec("capture").setIndicator(null,
res.getDrawable(R.drawable.ic_tab_capture))
.setContent(new Intent(this,CaptureActivity.class));
tabHost.addTab(spec);
// Upload tab
spec = tabHost.newTabSpec("upload").setIndicator(null,
res.getDrawable(R.drawable.ic_tab_capture))
.setContent(new Intent(this,ImageUpl开发者_运维技巧oad.class));
tabHost.addTab(spec);
To simplify my goal, my CaptureActivity.java includes the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.capture);
Intent intent = new Intent(this, ImageUpload.class);
startActivityForResult(intent, 0);
}
What I'm expecting is, the app should switch instantly to the second tab (ImageUpload activity) which works fine, BUT the tabs themselves disappear. I get the ImageUpload activity as stand-alone page, not within the tab itself.
Any idea what's going wrong there ?
First calling firing ImageUpload.java only fires ImageUpload.class but surely tabhost will disappear.
You need to fire your MainActivity-TabActivity where you added your two tabHost
1.ImageUpload
2.CaptureActivity
which will maintain your TabLayout
call intent like these
Intent i=new Intent(getApplicationContext(),MainActivity.class)//which is your mainActivity-Launcher
i.addFlags(Intent.FLAG_ACTIVITY_BRING_TO_FRONT);
startActivity(i);//will bring MainACtivity to Front
Now Main activity is already running so pointer directly goes to onNewIntent() inside Main Activity
Override onNewIntent() inside MainActivity
=====================================
public class MainActivity extends TabActivty
{
pubilc static TabHost tabhost;
public void onCreate()
{
//where you added your two tab spec
//added them
}
public void onNewIntent(intent)
{
super.onNewIntent(intent);
tabHost.setCurrentTab(1);//1-depends where you want to switch-tabIndexno, I assume Upload is at 2nd position (so "1")
Activity currentActivity=getCurrentActivity();
if(currentActivity instanceof Upload)
{
((upload)currentActivity).onCreate();//watever method you want to call
}
}
}
In the parent activity class where the tabhost is created I implemented a method like the one below:
public void switchTab(int tab){
tabHost.setCurrentTab(tab);
}
Inside of the tab that I would like to be able to switch internally to another tab I created the method below:
public void switchTabInActivity(int indexTabToSwitchTo){
YOURTABHOSTACTIVITY ParentActivity;
ParentActivity = (YOURTABHOSTACTIVITY) this.getParent();
ParentActivity.switchTab(indexTabToSwitchTo);
}
If you would like a good example of this code, you can take a look at my MintTrack project here and here.
精彩评论