Android:How to change opened tab dynamically

柔情痞子 提交于 2019-12-12 03:53:56

问题


I have an Android application which has four tabs (I use a main TabActivity with TabHost and TabSpecs). In one of my sub activity (activity opened in a tab), i need to open a tab not by clicking on the tab title and i don't know how to do this. For example, i have a button in my activity and when i click on it, it opens a different tab. For the moment, it is what i do:

Intent intent = new Intent(myActivity.this, myTabActivity.class);
intent.putExtra("ComeFrom", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Then in the TabActivity, if i get true reading the "ComeFrom" extra i open the wished tab but the problem is that it kills all the other activies. So, if someone knows a better (cleaner) way to do that trick, please tell me...


回答1:


You have to use TabHost's "setCurrentTab(...)" for that. In one of my projects, I created a static method in the main Activity (the one with the TabHost), named "swtichToTab(int tab)". In my subactivites (those inside the tabs) could then just call "MainActivity.switchToTab()" to trigger switching.

It may not be the cleanest method, I'm sure you can achieve this using broadcast intents too.




回答2:


Found an easier (I think) answer:

  1. on the TabActivity declare a public, static and self variable and populate it on the onCreate method. F.e.:

    public class TheActivity extends TabActivity {
        public static TheActivity self;
        ...
        @Override
        public void onCreate(Bundle savedInstanceState) {
            self=this;
    
  2. on any Activity running in a tab, when you want to change the one shown on your app. you can do this:

    TabHost tabHost = TheActivity.self.getTabHost();
    tabHost.setCurrentTab(0);
    

Worked ok for me, hope serves someone else!




回答3:


You can create a BroadcastReceiver and send a broadcast with the index of the tab as extra




回答4:


You can use views instead of activities for the content of the tabs. This way, the code is simpler and doesn't use as much memory. Plus, you then can use the setCurrentTab(tabIndex) method to easily switch between views.

I have a simple tutorial here. It has a tab activity with a list and map view. When you you click on an item in the list, the activity dynamically goes to the map view (using the setCurrentTab(tabIndex) method). You can easily modify this to have a button switch views.



来源:https://stackoverflow.com/questions/3942393/androidhow-to-change-opened-tab-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!