一种简单的底部导航fragmentTabhost

来源:互联网 发布:福建广电网络集团招标 编辑:程序博客网 时间:2024/06/16 21:25

本人一开始做底部导航的时候用的是RadioGoup,感觉比较麻烦,所以找来一个简单的底部导航分享给大家,废活不多说,上代码

activity代码public class MainActivity extends AppCompatActivity {    private FragmentTabHost mTabHost;    //定义一个布局    private LayoutInflater layoutInflater;    //定义数组来存放Fragment界面    //你有几个的底部导航按钮,就创建几个fragment,    private Class fragmentArray[] = {FragmentPage2.class,FragmentPage3.class,FragmentPage4.class,FragmentPage5.class};    //定义数组来存放按钮图片    //这里面可以放图片,也可以放选择器文件,放图片,就是点击没效果,如果想要点击变颜色,最好写几个选择器,再把选择器放里面    private int mImageViewArray[] = {R.drawable.tab_weitao,R.drawable.tab_xiaoxi,            R.drawable.tab_che,R.drawable.tab_wode};    //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按钮设置图标、文字和内容            TabHost.TabSpec spec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));            //将Tab按钮添加进Tab选项卡中            mTabHost.addTab(spec, 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.tabitem, null);        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);        imageView.setImageResource(mImageViewArray[index]);        TextView textView = (TextView) view.findViewById(R.id.textview);        textView.setText(mTextviewArray[index]);        return view;    }}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >   <RelativeLayout       android:layout_width="match_parent"       android:layout_height="40dp">   </RelativeLayout>    <FrameLayout        android:id="@+id/realtabcontent"        android:layout_width="match_parent"        android:layout_height="wrap_content"       />    <android.support.v4.app.FragmentTabHost        android:id="@android:id/tabhost"        android:layout_width="match_parent"        android:layout_height="50dp"        android:layout_alignParentBottom="true"        >        <FrameLayout            android:id="@android:id/tabcontent"            android:layout_width="match_parent"            android:layout_height="50dp"            />    </android.support.v4.app.FragmentTabHost></RelativeLayout>