开发者

Dynamically select the Tab Activity to launch when user clicks on a tab

I have seen many posts about using ActivityGroups for when you have nested activities used in a tab. In my case, I don't want to launch an activity from within an activity, but rather I want to dynamically decide (based on a flag value) what activity to launch everytime a user clicks on a tab.

I am trying something like this:

Tab activity class:

开发者_如何学C tabHost = (TabHost) findViewById(android.R.id.tabhost); 
 tabHost.setup();
 intent = new Intent().setClass(this, MyActivityGroup.class);
 TabHost.TabSpec spec = tabHost.newTabSpec("someTag");      
 View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_resource, getTabWidget(), false);
 TextView title = (TextView) tabIndicator.findViewById(R.id.tab_title); 
 title.setText(strTag);
 ImageView icon = (ImageView) tabIndicator.findViewById(R.id.tab_icon);
 icon.setImageResource(R.drawable.tab_icon);
 spec.setIndicator(tabIndicator).setContent(intent); 
 tabHost.addTab(spec);

MyActivityGroup class:

 public class MyActivityGroup extends ActivityGroup
 {
    public static MyActivityGroup group;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {  
       group = this;  
           SelectActivity();
   }  

      public void SelectActivity()
      {
        View view = null;
        Intent intent = null;
       Window w = null;
       LocalActivityManager l = getLocalActivityManager();
       if( CheckFlag() )
       {
           intent = new Intent(this, Activity1.class);
           w = l.startActivity("Activity 1", intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
           view = w.getDecorView();  
       }
       else
       {
       intent = new Intent(this,Activity2.class);
       w = l.startActivity("Activity 2", intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
           view = w.getDecorView();  
  }
  setContentView(view);  
  }

}

I added Activity1, Activity2 and MyActivityGroup to my manifest file. If in my tab class I replace MyActivityGroup with either Activity1 or Activity2 when I set the intent of the tab, then they launch fine. But using MyActivityGroup causes a crash in MyActivityGroup::SelectActivity at the call to startActivity.

Any suggestions? :s


Turns out I had to call

l.dispatchCreate(savedInstanceState);

before SelectActivity(). Hope this helps someone!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜