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

假如想象 提交于 2019-11-30 09:59:50

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

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.

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