直接上代码
布局文件 activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_weight="1"
android:background="@color/bg_color"
android:layout_width="match_parent"
android:layout_height="0dip"/>
<com.example.ruolan.letgo.widget.FragmentTabHost
android:id="@android:id/tabhost"
android:background="@color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_weight="0"
//
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"></FrameLayout>
</com.example.ruolan.letgo.widget.FragmentTabHost>
</LinearLayout>
操作共分三步
第一步是:activity继承FragmentActivity
第二步是:调用setup()方法
第三步是:添加tabSpec
MainActivity中的主要方法:
mInflater = LayoutInflater.from(this);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
//调用setup()方法
mTabHost.setup(this,getSupportFragmentManager(),R.id.realtabcontent);
//新建TabSpec
TabHost.TabSpec tabSpec = mTabHost.newTabSpec("主页");
//创建新的View,也就是刚才前面讲的View
View view = mInflater.inflate(R.layout.tab_indicator,null);
img = (ImageView) view.findViewById(R.id.icon_tab);
text = (TextView) view.findViewById(R.id.text_indicator);
img.setBackgroundResource(R.mipmap.icon_home);
text.setText(R.string.home);
tabSpec.setIndicator(view);
//添加tabSpec,这里我们要传三个参数
//分别是tabSpec、class、null
mTabHost.addTab(tabSpec,HomeFragment.class,null);