Add Tabs to Android Application using the layout/main.xml file

半城伤御伤魂 提交于 2019-12-03 20:27:06

I have looked it up and found http://developer.android.com/resources/tutorials/views/hello-tabwidget.html on the Android developer site; however, that doesn't use XML for defining the layout of the tabs.

Yes, it does. See step #4.


UPDATE

Google reorganized their documentation and got rid of this tutorial. You can see the use of XML for defining the tabs in TabWidget in this sample project.

I've run into a situation where the TabWidget layout didn't do what I needed, so I faked it up with a ViewFlipper and a RadioGroup. That way, I could define the content of the tabs (each view in the ViewFlipper) using includes (like in Farray's answer).

The tabs themselves were the RadioButtons in the RadioGroup - you just have an OnCheckedChangeListener in your code and set the ViewFlipper's displayed child accordingly. You can define the RadioButton layout in XML (with text or images or whatever).

Here's a pseudo-layout where the tabs use images:

<LinearLayout>
    <ViewFlipper android:id="@+id/viewFlipper">
        <include android:id="@+id/tab1Content" layout="@layout/tab1Layout" />
        <include android:id="@+id/tab2Content" layout="@layout/tab2Layout" />
        <include android:id="@+id/tab3Content" layout="@layout/tab3Layout" />
    </ViewFlipper>
    <LinearLayout>
        <RadioGroup android:id="@+id/radgroup1" android:orientation="horizontal">
          <RadioButton android:id="@+id/rad1" android:button="@drawable/tab1" />
          <RadioButton android:id="@+id/rad2" android:button="@drawable/tab2" />
          <RadioButton android:id="@+id/rad3" android:button="@drawable/tab3" />
        </RadioGroup>
    </LinearLayout>
</LinearLayout>

And here's the listener:

    private OnCheckedChangeListener onRadioButtonCheckedChanged = new OnCheckedChangeListener(){
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {
        switch(checkedId)
        {
            case(R.id.rad2):
                viewFlipper.setDisplayedChild(1);
            break;
            case(R.id.rad3):
                viewFlipper.setDisplayedChild(2);
            break;
            default:
                viewFlipper.setDisplayedChild(0);
            break;
        }
    }
};

The TabWidget implementation is pretty rigid -- you don't have much control over layout.

If you want to create your own custom tabs, your best bet is to create a custom layout and call it from the activities that you want to have these "tabs". You can call reusable layouts in XML with <include layout="@layout/my_tab_layout" /> and then write your own initialization code in a reusable class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!