0

我正在向我的应用程序添加一个新的选项卡布局。我的应用有 4 个活动。

之前,导航是通过显示在活动中的按钮完成的,例如活动 1 中的按钮使您转到第 4 部分。每个按钮都以新的意图启动一个新活动。要返回用户可以点击他的本机设备返回按钮。

按钮示例:

Button b1= (Button) findViewById(R.id.b1);
    b1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(this, ActivityTab4.class);
            startActivity(i);                           
        }
   });

现在,使用 tabhost,用户直接进入期望活动,每个活动都是我的 tabhost 的子项。但是,我仍然需要在我的布局中保留一些直接跳转到特定活动的按钮。

这些按钮的问题在于,当它们开始一个新活动时,tabhost 会消失。我需要一直保留它。

那么我怎样才能正常使用tabhost,但在它的顶部还使用我的部分布局内的自定义按钮,当我点击它们时会保留tabhost?

我的 tabhost 结构非常基本:

public class TabWidget extends TabActivity {    

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.global_tabs);
    setTabs() ;     
    }   

private void setTabs() {        
    addTab("Act1", R.drawable.tab1, ActivityTab1.class);
    addTab("Act2", R.drawable.tab2, ActivityTab2.class);        
    addTab("Act3", R.drawable.tab1, ActivityTab3.class);
    addTab("Act4", R.drawable.tab2, ActivityTab4.class);
    }

private void addTab(String labelId, int drawableId, Class<?> c) {

    TabHost tabHost = getTabHost();
    Intent intent = new Intent(this, c);
    TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId); 

    // SET TITLETAB
    View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
    TextView title = (TextView) tabIndicator.findViewById(R.id.titleTab);
    title.setText(labelId);

    // SET IMAGETAB
    ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
    icon.setImageResource(drawableId);

    spec.setIndicator(tabIndicator);
    spec.setContent(intent);
    tabHost.addTab(spec);
    }}

谢谢你的帮助

编辑:我宁愿避免使用片段,因为这将花费我大量时间来实现它们,并且最重要的是使其与 API<11 兼容

4

2 回答 2

1

好的,我找到了,感谢这个答案:tabHost 的 setCurrentTab

基本上在主要的 tabhost 活动中,添加这个

private static Main theInstance;

public static Main getInstance() {
    return Main.theInstance;
}

public Main () {
    Main.theInstance = this;
}

在孩子中,您可以有一个按钮将用户发送到任何选项卡+相应的活动:

Button b1_3= (Button) findViewById(R.id.b1_3);
    b1_3.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            TabWidget.getInstance().getTabHost().setCurrentTab(3);
        }
   });
于 2013-02-14T10:08:32.203 回答
0

为什么你使用 tabhost 和活动而不是 Fragments?我认为您会发现 Fragments 更适合您正在尝试做的事情。

至于您的问题-您可以使用切换显示的选项卡

 void   setCurrentTab(int index) 
 void   setCurrentTabByTag(String tag)

因此无需在按下按钮时手动启动活动,只需使用这些方法切换显示的选项卡即可。

于 2013-02-13T14:46:57.060 回答