1.先展示运行效果截图。
2.展示Android项目文件的构成。
3.布局activity_main.xml展示:
<?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" android:orientation="vertical" > <FrameLayout android:id="@+id/realtabcontent" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" /> <android.support.v4.app.FragmentTabHost android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/maintab_toolbar_bg" > <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0" /> </android.support.v4.app.FragmentTabHost> </LinearLayout>
4. Fragment1.java代码展示:
package com.example.fragmentdemo2; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Fragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment1, null); } }
5.MainActivity.java主要代码展示:
public class MainActivity extends FragmentActivity { // 定义FragmentTabHost对象 private FragmentTabHost mTabHost; // 定义一个布局 private LayoutInflater layoutInflater; // 定义一个数组来存放Fragment界面 private Class fragmentArray[] = { Fragment1.class, Fragment2.class, Fragment3.class }; // 定义数组来存放按钮图片 private int mImageViewArray[] = { R.drawable.tab_finding, R.drawable.tab_recording, R.drawable.tab_me }; // Tab选项卡的文字 private String mTextViewArray[] = { "发现", "更多", "我的" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); }
private void initView() { // 实例化布局对象 layoutInflater = LayoutInflater.from(this); // 实例化TabHost对象,得到TabHost mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); // 得到fragment的个数 int count = fragmentArray.length; for (int i = 0; i < count; i++) { // 为每一个Tab按钮设置图标、文字和内容 TabSpec tabSpec = mTabHost.newTabSpec(mTextViewArray[i]) .setIndicator(getTabItemView(i)); // 将Tab按钮添加进Tab选项卡中 mTabHost.addTab(tabSpec, fragmentArray[i], null); // 设置Tab按钮的背景 mTabHost.getTabWidget().getChildAt(i) .setBackgroundResource(R.drawable.selector_tab_background); } }
private View getTabItemView(int index) { View view = layoutInflater.inflate(R.layout.tab_item_view, null); ImageView imageview = (ImageView) view.findViewById(R.id.tabimage); imageview.setImageResource(mImageViewArray[index]); TextView textview = (TextView) view.findViewById(R.id.textview); textview.setText(mTextViewArray[index]); return view; }
6.附上源码下载地址