Android: How to build tabs like the ones show on Android UI Page

后端 未结 2 394
生来不讨喜
生来不讨喜 2020-12-31 23:49

So android goes out of its way to build this nice UI guide for everyone to use. But I don\'t see anywhere where it shows code examples of how to build these elements.

相关标签:
2条回答
  • 2021-01-01 00:22

    do something like this.

    this is a full working code. enjoy

    somewhere in oncreate method of activity extending Tabactivity

      tabHost = getTabHost();
      Intent intent;
      intent = new Intent().setClass(this, FirstActvity.class);
      setupTab("NearBy", intent, R.drawable.firsttabdrawable);
      intent = new Intent().setClass(this, SecondActivity.class);
      setupTab("History", intent, R.drawable.secondtabdrawable);
      intent = new Intent().setClass(this, ThirdActivity.class);
      setupTab("Setting", intent, R.drawable.thirdtabdrawable);
    

    define setupTab methods as

      private void setupTab(String tag, Intent intent, int selectorId) {
      View tabView = LayoutInflater.from(tabHost.getContext()).inflate(R.layout.view, null);
      tabView.setBackgroundResource(selectorId);
      TabSpec setContent = tabHost.newTabSpec(tag).setIndicator(tabView).setContent(intent);
      tabHost.addTab(setContent);
      }
    

    view.xml as

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
    >
    </LinearLayout>
    

    and firsttabdrawable.xml in drawable folder as

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
       <!-- When selected, use grey -->
       <item android:drawable="@drawable/selectedfirsttabimage"
          android:state_selected="true" />
       <!-- When not selected, use white-->
       <item android:drawable="@drawable/notselectedfirsttabimage" />
    </selector>
    

    define secondtabdrawable.xml and thirddrawable.xml in the same way

    0 讨论(0)
  • 2021-01-01 00:22

    The tabs you need are part of the ActionBar. Specifically they are displayed when the ActionBar is in Navigation Tab mode.

    http://developer.android.com/guide/topics/ui/actionbar.html (see under "Adding Navigation Tabs")

    You may want to use www.ActionbarSherlock.com which is a library that will give you the ActionBar on nearly all versions of Android. It works the same as the official one, and includes the tabs.

    Do not use the TabActivity any more, it's old and being deprecated. ActionBar is the future.

    0 讨论(0)
提交回复
热议问题