2012-12-03 76 views
1

我必须在所有选项卡中添加n个具有相同布局(在xml中声明为llItemList)的选项卡。在下面的代码片段中,我创建了n个选项卡。所有布局使用llItemList的相同副本,而不是选项卡自己的副本。你能否让我知道如何在动态创建的所有选项卡中创建一个单独的llItemList副本。 由于提前Android - 动态添加选项卡

//--------------------------------- 
    // insert the tabs dynamically 
    //--------------------------------- 
    for (int i=1; i<=n; i++){ 
     final String tabName = "tab" + Integer.toString(i); 
     final TabSpec ourSpec = th.newTabSpec(tabName); 
     ourSpec.setContent(new TabHost.TabContentFactory() { 
      public View createTabContent(String tag) { 
      ourSpec.setContent(R.id.llItemList); 
      TextView text = new TextView(NewTicket.this); 
      String tabText = tabName; 
      text.setText("You've created a new tab " + tabText); 
      return (text); 
      } 
     }); 
     ourSpec.setIndicator(tabName); 
     th.addTab(ourSpec); 
    } 

回答

1

您应该指定一个TabSpec通过指定

  • 视图的ID,
  • 创建视图内容的TabHost.TabContentFactory

你的代码都可以!

你的代码更改为以下之一:

for (int i=1; i<=n; i++){ 
    final String tabName = "tab" + Integer.toString(i); 
    final TabSpec ourSpec = th.newTabSpec(tabName); 
    ourSpec.setContent(new TabHost.TabContentFactory() { 
     public View createTabContent(String tag) { 
      TextView text = new TextView(NewTicket.this); 
      String tabText = tabName; 
      text.setText("You've created a new tab " + tabText); 
      return (text); 
     } 
    }); 
    ourSpec.setIndicator(tabName); 
    th.addTab(ourSpec); 
} 

for (int i=1; i<=n; i++){ 
    final String tabName = "tab" + Integer.toString(i); 
    final TabSpec ourSpec = th.newTabSpec(tabName); 
    ourSpec.setContent(R.id.llItemList); 
    ourSpec.setIndicator(tabName); 
    th.addTab(ourSpec); 
} 

编辑:

要保留的ListView相同的实例,在您的评论中提到,请执行以下操作:

  1. 注册一个TabHost.OnTabChangeListener
  2. 当捏的变化,你应该首先调用removeView()上ListView控件的当前父,然后addView()它为新的父。
+0

我已经使用了第二个选项。现在我有一个列表视图附加到布局。这将是所有动态选项卡的常见布局。你能提供这种情况下的任何样本吗? – user1822729

+0

你的意思是所有的标签应该有相同的ListView的**实例**? –

+0

正是这就是我正在寻找 – user1822729