Pergunta

I found a lot of examples to create tabs using an xml file in android, but I need to create multiple tabs programmatically. Please guide me.

<TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:tag="tab0"
            android:text="Tab 1"
            android:background="@android:drawable/btn_star_big_on"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            />
        <TextView
            android:tag="tab1"
            android:text="Tab 2"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            />
        <TextView
            android:tag="tab2"
            android:text="Tab 3"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            />

    </TabWidget>

How can I write this programmatically instead of the above xml code.

Foi útil?

Solução

Check Tab With Swipe example. It has implementation of tabs without xml files.

But there is XML layout for each fragment. You can drop it as per your requirement.

Outras dicas

In your TabActivity:

private void addTab(String labelId, int drawableId, Class<?> c)
{
  Intent intent=new Intent(this, c);
  TabHost.TabSpec spec=Your_TabHost.newTabSpec("tab"+labelId);

  View tabIndicator=LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
  TextView title=(TextView)tabIndicator.findViewById(R.id.title);
  title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
  title.setText(labelId);
  ImageView icon=(ImageView)tabIndicator.findViewById(R.id.icon);
  icon.setImageResource(drawableId);

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

Add tab(s) via this way(Still in TabActivity):

addTab("Your tab title", R.drawable.your_tab_icon, SomeActivity.class);

But I still strongly suggest you to use ActionBarSherlock in android lower than 4.0, since Tab have been deprecated...

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top