문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top