android底部选项卡(二)FragmentTabHost +Fragment 实现

时间:2021-02-19 06:26:32

前面一篇博客中提到, 使用 TabHost实现底部选项栏,但是TabHost已经过时点击打开链接

TabHost实现底部选项栏切换的的是Activity,而FragmentTabHost 切换的则是Fragment,相比之下更加灵活,性能更加优越

FragmentTabHost +Fragment 不仅能在不同选项卡间快速切换,而且还能保存其它选项卡之前的状态

1、FragmentTabHost 的Xml文件定义如下:

需要注意的是:FragmentTabHost 的id必须指定为系统的“@android:id/tabhost”

FragmentTabHost 上面的FrameLayout布局是用来填充对应Fragment的容器

<?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" >
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>


2.java逻辑

package com.example.fragmenttabhost;

import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {
private LayoutInflater inflater;
private FragmentTabHost mTabHost;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inflater=LayoutInflater.from(this);

mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(getApplicationContext(), getSupportFragmentManager(),
R.id.realtabcontent);


// 添加tab名称和图标
View indicator = getIndicatorView("我的联系人", R.drawable.tab_main_nav_me);
TabSpec firstSpec = mTabHost.newTabSpec("myContact").setIndicator(
indicator);
mTabHost.addTab(firstSpec, FirstFragment.class, null);

// 添加tab名称和图标
View indicator2 = getIndicatorView("我的读书", R.drawable.tab_main_nav_book);
TabSpec secondSpec = mTabHost.newTabSpec("myRead").setIndicator(
indicator2);
mTabHost.addTab(secondSpec, SecondFragment.class, null);
}

/**
* 设置底部选项卡
*/
private View getIndicatorView(String name, int iconid) {
View view = inflater.inflate(R.layout.nav_tab, null);
ImageView ivicon = (ImageView) view.findViewById(R.id.ivIcon);
TextView tvtitle = (TextView) view.findViewById(R.id.tvTitle);
ivicon.setImageResource(iconid);
tvtitle.setText(name);
return view;
}
}

源码下载地址 http://download.csdn.net/detail/lang791534167/6837533