FragmentTabHost控件的用法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FragmentTabHost控件的用法相关的知识,希望对你有一定的参考价值。

主要包括:

(1) 自定义Tab的图片资源和去掉分割线.
(2) 缓存Fragment的布局, 减少填充.

在切换页面时, 控件会调用Fragment的onCreateView, 重新创建页面.
通过缓存页面, 可以增强性能.

1. 布局

FragmentTabHost是原生控件, 并不需要添加其他的maven库.

包括标签组Tabs和页面TabContainer, 标签组固定大小, 页面填充.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost
    android:id="@android:id/tabhost"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom"/>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

    </LinearLayout>

</android.support.v4.app.FragmentTabHost>

注意控件的id必须是Android提供的标准id, 即”@android:id”.

Fragment布局, 包含一行文字提示.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <TextView
        android:id="@+id/tab_tv_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="40sp"
        tools:text="Test"/>

</LinearLayout>

Tab布局, 包含一个图片控件.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/tab_iv_image"
        android:padding="12dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@null"
        tools:src="@drawable/tab_assistant"/>

</LinearLayout>

2. 主页

setup设置页面组合, 却掉分割线etDividerDrawable(null), 设置Tab.

使用自定义的图片资源, newTabSpec设置Fragment的Tag标签.

/**
 * 主页, 切换Tab标签显示不同页面.
 *
 * @author C.L.Wang
 */
public class MainActivity extends AppCompatActivity {

    @Bind(android.R.id.tabhost) FragmentTabHost mTabHost;

    // 图片
    @DrawableRes
    private int mImages[] = {
            R.drawable.tab_counter,
            R.drawable.tab_assistant,
            R.drawable.tab_contest,
            R.drawable.tab_center
    };

    // 标题
    private String mFragmentTags[] = {
            "counter",
            "assistant",
            "contest",
            "center"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);

        mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
        mTabHost.getTabWidget().setDividerDrawable(null); // 去掉分割线

        for (int i = 0; i < mImages.length; i++) {
            // Tab按钮添加文字和图片
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mFragmentTags[i]).setIndicator(getImageView(i));
            // 添加Fragment
            mTabHost.addTab(tabSpec, FragmentTab.class, null);
            // 设置Tab按钮的背景
            mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.color.pedo_actionbar_bkg);
        }
    }

    // 获得图片资源
    private View getImageView(int index) {
        @SuppressLint("InflateParams")
        View view = getLayoutInflater().inflate(R.layout.view_tab_indicator, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.tab_iv_image);
        imageView.setImageResource(mImages[index]);
        return view;
    }
}

3. 切换页

显示不同Tag标签. 缓存页面, 注意关联前, 删除父控件关联. 页面显示Tag信息.

/**
 * Tab的Fragment
 * <p/>
 * Created by wangchenlong on 15/12/28.
 */
public class FragmentTab extends Fragment {

    @Bind(R.id.tab_tv_text) TextView mTvText;

    private View mViewContent; // 缓存视图内容

    @Nullable @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mViewContent == null) {
            mViewContent = inflater.inflate(R.layout.fragment_tab, container, false);
        }

        // 缓存View判断是否含有parent, 如果有需要从parent删除, 否则发生已有parent的错误.
        ViewGroup parent = (ViewGroup) mViewContent.getParent();
        if (parent != null) {
            parent.removeView(mViewContent);
        }

        ButterKnife.bind(this, mViewContent);
        return mViewContent;
    }

    @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 显示Fragment的Tag信息
        mTvText.setText(String.valueOf("Page: " + getTag()));
    }

    @Override public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}

技术分享

OK, That’s all! 熟练使用控件很重要. Enjoy It!

《《《《2》》》》

由以下布局文件main.xml<FrameLayout>的位置决定
 
[html]  
<?xml version="1.0" encoding="utf-8"?>  
<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="0dip"  
        android:layout_weight="1" />  
      
    <android.support.v4.app.FragmentTabHost  
        android:id="@android:id/tabhost"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content">  
          
        <TabWidget   
            android:id="@android:id/tabs"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:orientation="horizontal"/>  
    </android.support.v4.app.FragmentTabHost>  
      
</LinearLayout>  
 
创建一个类继承FragmentActivity
 
[java]  
package com.example.tabhostdemo;  
  
import android.os.Bundle;  
import android.support.v4.app.FragmentActivity;  
import android.support.v4.app.FragmentTabHost;  
import android.view.View;  
import android.widget.TextView;  
  
import com.example.tabhost.FirstFragment;  
import com.example.tabhost.ThirdFragment;  
import com.example.tabhost.secondFragment;  
  
public class MainActivity extends FragmentActivity {  
  
    private FragmentTabHost mTabHost = null;;  
    private View indicator = null;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
  
        setContentView(R.layout.main);  
  
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);  
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);  
  
        // 添加tab名称和图标  
        indicator = getIndicatorView("我的联系人", R.layout.mycontact_indicator);  
        mTabHost.addTab(mTabHost.newTabSpec("myContact")  
                .setIndicator(indicator), FirstFragment.class, null);  
  
        indicator = getIndicatorView("陌生人", R.layout.strangercontact_indicator);  
        mTabHost.addTab(  
                mTabHost.newTabSpec("stranger").setIndicator(indicator),  
                secondFragment.class, null);  
  
        indicator = getIndicatorView("常联系人", R.layout.alwayscontact_indicator);  
        mTabHost.addTab(  
                mTabHost.newTabSpec("alwaysContact").setIndicator(indicator),  
                ThirdFragment.class, null);  
    }  
  
    private View getIndicatorView(String name, int layoutId) {  
        View v = getLayoutInflater().inflate(layoutId, null);  
        TextView tv = (TextView) v.findViewById(R.id.tabText);  
        tv.setText(name);  
        return v;  
    }  
  
    @Override  
    protected void onDestroy() {  
        // TODO Auto-generated method stub  
        super.onDestroy();  
        mTabHost = null;  
    }  
}  
第一个Tab的布局文件    存放两张图片,字体颜色
alwayscontact_indicator.xml文件
[html] view plaincopy
<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:layout_gravity="center"   
    android:gravity="center">  
  
    <TextView   
        android:id="@+id/tabText"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:focusable="true"  
        android:drawableTop="@drawable/mycontact_selector"  
        android:textColor="@drawable/tabitem_txt_sel"/>  
</LinearLayout>  
 
mycontact_selector.xml文件
[html]  
<?xml version="1.0" encoding="utf-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android" >      
    <!-- Non focused states -->  
    <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/mycontact" />  
    <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/mycontact_sel" />  
    <!-- Focused states -->  
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/mycontact_sel" />  
    <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/mycontact_sel" />  
    <!-- Pressed -->  
    <item android:state_selected="true" android:state_pressed="true" android:drawable="@drawable/mycontact_sel" />  
    <item android:state_pressed="true" android:drawable="@drawable/mycontact_sel" />    
</selector>  
 
tabitem_txt_sel.xml文件
[html] 
<?xml version="1.0" encoding="utf-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android" >      
    <!-- Non focused states -->  
    <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:color="#A4A4A4" />  
    <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:color="#00A3F5" />  
    <!-- Focused states -->  
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:color="#00A3F5" />  
    <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:color="#00A3F5" />  
    <!-- Pressed -->  
    <item android:state_selected="true" android:state_pressed="true" android:color="#00A3F5" />  
    <item android:state_pressed="true" android:color="#00A3F5" />   
</selector>  
其它的tab文件定义也是类似的,看下最后的效果图
技术分享

 

以上是关于FragmentTabHost控件的用法的主要内容,如果未能解决你的问题,请参考以下文章

FragmentTabHost + Fragment 使用小记

FragmentTabHost+Fragment搭建应用主框架

FragmentTabHost+Fragment搭建应用主框架

FragmentTabHost的使用方法总结

FragmentTabHostTopDemoFragmentTabHost固定宽度且居中

android中 Fragment+FragmentTabHost