Android FragmentTabHost的简单使用

FragmentTabHost 实现底部android底部菜单的切换

效果图:


Android FragmentTabHost的简单使用
 布局文件:

<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_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"
        android:background="@drawable/maintab_toolbar_bg" >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp" />
    </android.support.v4.app.FragmentTabHost>

</LinearLayout>

 MainActivity:

public class MainActivity extends FragmentActivity {
	private FragmentTabHost mFragmentTabHost;
	private LayoutInflater mInflater;
	private String[] tabs = { "推荐", "仓库", "搜索", "我的" };
	private int[] drawables = { R.drawable.tab_home_btn,
			R.drawable.tab_more_btn, R.drawable.tab_square_btn,
			R.drawable.tab_selfinfo_btn };
	private Class<?>[] fragments = { HomeFragment.class, ClassisFragment.class,
			SearchFragment.class, SelfishFragment.class };
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext=this;
		mInflater=getLayoutInflater();
		mFragmentTabHost=(FragmentTabHost) findViewById(android.R.id.tabhost);
		mFragmentTabHost.setup(this, getSupportFragmentManager(),
				R.id.realtabcontent);
		for (int i = 0; i < fragments.length; i++) {
			mFragmentTabHost.addTab(mFragmentTabHost.newTabSpec(tabs[i])
					.setIndicator(getTabItemView(i)), fragments[i], null);

			mFragmentTabHost.getTabWidget().getChildAt(i)
					.setBackgroundResource(R.drawable.selector_tab_background);
		}
	}
	/*
	 * 为每个TabItem添加显示信息
	 */
	private View getTabItemView(int i) {
		View view = mInflater.inflate(R.layout.tab_item_view, null);
		ImageView image = (ImageView) view.findViewById(R.id.tab_item_image);
		image.setImageResource(drawables[i]);
		TextView text = (TextView) view.findViewById(R.id.tab_item_text);
		text.setText(tabs[i]);
		return view;
	}

}



 

相关推荐