之前一直使用RadioGroup方式和直接使用LinearLayout来实现底部标签栏,
后面发现FragmentTabhost是如此的简单,现在写文章记录下来,免得忘记了,反正我是对自己的记忆不抱任何希望的
1、创建布局文件
<?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/fragment_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
2、MainActivity代码,设置FragmentTabHost每个Tab以及所对应的Fragment
public class MainActivity extends FragmentActivity {
private final String[] titles = {"One", "Two", "Three", "Four"};
private Class<Fragment>[] framents = new Class[]{
Fragment001.class,
Fragment002.class,
Fragment003.class,
Fragment004.class,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化TabHost
FragmentTabHost tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), R.id.fragment_content);
//TabHost添加对应的View,并设置对应的Fragment
for (int i = 0; i < 4; i++) {//添加4个tab
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText(titles[i]);
//创建一个测量规则,也是添加对应tab的View
TabHost.TabSpec tabSpec = tabHost.newTabSpec(titles[i]).setIndicator(tv);//tv可替换为任何View,此处求简单
//设置测量规则,并设置tab对应的Fragment
tabHost.addTab(tabSpec, framents[i], null);
}
}
}
注意:为了切换时Tab能保存Fragment里的数据,需要给对应控件添加id