FragmentTabHost实现Fragment的tab效果

来源:互联网 发布:mysql实用教程 pdf 编辑:程序博客网 时间:2024/05/16 17:03

TabHost效果

public class MainActivity extends FragmentActivity{     //定义FragmentTabHost对象    private FragmentTabHost mTabHost;    //定义一个布局    private LayoutInflater layoutInflater;    //定义数组来存放Fragment界面    @SuppressWarnings("rawtypes")    private Class fragmentArray[] = {InspectFragment.class,ExecuteFragment.class,TaskFragment.class,ExitFragment.class};    //定义数组来存放按钮图片    private int mImageViewArray[] = {R.drawable.tab_more_btn,R.drawable.tab_home_btn,R.drawable.tab_selfinfo_btn,R.drawable.tab_message_btn};        public void onCreate(Bundle savedInstanceState) {    this.requestWindowFeature(Window.FEATURE_NO_TITLE);        super.onCreate(savedInstanceState);        setContentView(R.layout.main_tab_layout);        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(i+"").setIndicator(getTabItemView(i));            //将Tab按钮添加进Tab选项卡中            mTabHost.addTab(tabSpec, fragmentArray[i], null);        }    }    /**     * 给Tab按钮设置图标和文字     */    private View getTabItemView(int index){        View view = layoutInflater.inflate(R.layout.main_tab_item, null);        TextView tab_item_view = (TextView) view.findViewById(R.id.tab_item_view);        tab_item_view.setBackgroundResource(mImageViewArray[index]);        return view;    }}


注意在Fragment导包的时候要导import android.support.v4.app.Fragment;


图标用背景选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/xpd" android:state_selected="true"/>    <item android:drawable="@drawable/pd"/></selector>

布局文件

    <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="50dp"            android:layout_weight="0" />    </android.support.v4.app.FragmentTabHost>    <FrameLayout        android:id="@+id/realtabcontent"        android:layout_width="fill_parent"        android:layout_height="0dip"        android:layout_weight="1" />


0 0
原创粉丝点击