这里的关键是在TabHost布局中加入一个FrameLayout的布局,在FrameLayout里再加入我们定义的:动态、发现、分享、家园、更多这几个Tab选项所对应的Fragment。
下面是在MainActivity.onCreate函数里调用initGui这个函数,在这个函数里添加Tab选项:
private void initGui() { tabHost = (TabHost)findViewById(android.R.id.tabhost); tabHost.setup();//去掉底端的白线 tabHost.setPadding(tabHost.getPaddingLeft(), tabHost.getPaddingTop(), tabHost.getPaddingRight(), tabHost.getPaddingBottom() - 3); TabWidget tabWidget = tabHost.getTabWidget(); // 添加底部的Table选项 addDynamicTab(tabHost, tabWidget); addFindTab(tabHost, tabWidget); addShareTab(tabHost, tabWidget); addSnsTab(tabHost, tabWidget); addMoreTab(tabHost, tabWidget); tabHost.setCurrentTab(0); } |
对于每个具体的Tab选项,处理方式基本类似,都是找到布局文件,载入图片、写上文字,代码如下所示:
privatevoidaddDynamicTab(TabHosthost,TabWidgettw){ RelativeLayoutindicator=(RelativeLayout)LayoutInflater.from(this).inflate(R.layout.tab_bottom_indicator,tw,false); ImageViewimg=(ImageView)indicator.getChildAt(0); img.setBackgroundResource(R.drawable.main_bottom_tab1); TextViewtabText=(TextView)indicator.getChildAt(1); tabText.setText(getResources().getString(R.string.j_main_tab_dynamic)); tabText.setTextColor(getResources().getColor(R.color.white)); TabSpectabSpec=host.newTabSpec(MAIN_TAB_DYNAMIC); tabSpec.setIndicator(indicator); tabSpec.setContent(R.id.j_dynamicFragment); host.addTab(tabSpec); } |
这里只给出了动态Tab的代码,其他的类似,大家可以举一反三。
对于每个Tab的外观定义,由下面的布局文件来规定:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="1" android:orientation="vertical" android:background="@drawable/tab_bottom_selector" android:paddingTop="6dip" android:paddingBottom="4dip" android:gravity="center_horizontal"> <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" /> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:textSize="14sp" android:textColor="@color/black" /> </RelativeLayout> |
大家可以看到,主要就是一个图片和一个标题。
至此一个虽然简单,但是却包含了基本应用的框架就正式做好了,下图是程序运行效果图:
相关文章: