开发者

switching tabs programmatically android

I have two tabs reports and charts. In charts tab i have another activity 'graph' being shown on click of a button. Now when in 'graph' activity, on click of a button, i want to switch to the reports tab an not come back to the charts tab.

So in activity 'graph' I thought i should do this,

开发者_如何学运维
final TabHost tabHost =  (TabHost) getParent().findViewById(android.R.id.tabHost);
    btnBackToReports.setOnClickListener(new OnClickListener() {  
        public void onClick(View v) {
            tabHost.setCurrentTab(1);
        }
    });

This probably would work if the tabhost was being created in the xml of the TabActivity class. But I'm not create the tabhost in the xml. So, I cannot do findViewById(android.R.id.tabhost). I'm creating it in the java file like this,

TabHost tabHost = getTabHost();
TabHost.TabSpec chartsSpec = tabHost.newTabSpec("charts").setIndicator("Charts")
                                    .setContent(new Intent(this, Charts.class));
                                    tabHost.addTab(chartsSpec);

So how do i now get the id of the tabHost? Is it possible to set an ID to tabHost programmatically?

Any help is greatly appreciated.


Hm, there are many solutions for this.

Variant 1) (removed, was stupid)

Variant 2) you could send a Broadcast from the activity which want to change the tab, to the activity which host the tab and in the Broadcast Receiver you have access to the tabhost.


You cannot change the UI of one Activity from another (well, it might be possible, but don't try it).

The best option would be to use startActivityForResult when starting your graph activity. Then when someone clicks your button, you can do

public void onClick(View v) {
    Intent intent = new Intent();
    intent.putExtra("selected_tab", 1);
    setResult(Activity.RESULT_OK);
    finish();
}

and in your activity with the tabs

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK && data != null) {
        int selectedTab = intent.getIntExtra("selected_tab", 0);
        if (selectedTab == 1) {
            tabHost.setCurrentTab(1);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜