天天看點

FragmentTabHostBottomDemo【FragmentTabHost + Fragment實作底部頁籤】

版權聲明:本文為HaiyuKing原創文章,轉載請注明出處!

前言

使用FragmentTabHost實作底部頁籤效果。

備注:該Demo主要是示範FragmentTabHost的一些設定和部分功能,實際中需要參考其他Demo。

效果圖

FragmentTabHostBottomDemo【FragmentTabHost + Fragment實作底部頁籤】

代碼分析

1、該Demo中采用的是FragmentTabHost的布局方案之一【命名為非正常布局寫法】;【建議使用正常布局寫法,見《FragmentTabHostTopDemo【FragmentTabHost固定寬度且居中】》】

2、未使用自定義的FragmentTabHost;【建議使用自定義的FragmentTabHost,見《FragmentTabHostUnderLineDemo【FragmentTabHost帶下劃線】》】

原因是FragmentTabHost切換時執行的是attach/detach,而不是show/hide。而atach觸發的執行順序:attach()->onCreateView()->onActivityCreated()->onStart()->onResume()

使用hide()方法隻是隐藏了fragment的view并沒有将view從viewtree中删除,随後可用show()方法将view設定為顯示。

3、ContactFragment示範的是:使用FragmentTabHost時,Fragment之間切換時每次都會調用onCreateView方法,導緻每次Fragment的布局都重繪,無法保持Fragment原有狀态。

小結:對于2和3,都是解決切換fragment的時候重載的問題,兩種方案各有利弊,選擇其中一個即可。

4、示範設定頁籤區域的自定義寬度和高度;

5、示範初始化時、切換時傳參;【切換時傳參,可能一般用不到】

6、自定義頁籤子項類【擷取底部頁籤的布局執行個體并初始化設定、更新文字顔色】;【這個思路參考别人的,思路比較好】【更新每個頁籤的背景需要額外寫另外的方案,見《FragmentTabHostTopDemo【FragmentTabHost固定寬度且居中】》】

7、示範點選頁籤子項不切換到相應的fragment,而是打開一個新的界面;【用作個别情況】

使用步驟

一、項目組織結構圖

FragmentTabHostBottomDemo【FragmentTabHost + Fragment實作底部頁籤】
FragmentTabHostBottomDemo【FragmentTabHost + Fragment實作底部頁籤】

注意事項:

1、  導入類檔案後需要change包名以及重新import R檔案路徑

2、  Values目錄下的檔案(strings.xml、dimens.xml、colors.xml等),如果項目中存在,則複制裡面的内容,不要整個覆寫

二、導入步驟

将頁籤子項布局檔案tab_bottom_item.xml檔案複制到項目中

<?xml version="1.0" encoding="utf-8"?>
<!-- 底部頁籤區域的子頁籤布局檔案 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/tab_bg_normal"
    android:gravity="center" >
    
    <!-- android:checkMark="?android:attr/listChoiceIndicatorMultiple"代表多選
         android:checkMark="?android:attr/listChoiceIndicatorSingle" 代表單選 
         該屬性不添加的話,不會顯示方框或者圓點
       -->
       
       <!-- android:drawableTop的屬性值使用drawable目錄下的selector選擇器 -->
       <!-- android:tag="tag1"用于checkedTextview的索引 -->
       
       <!-- 頁籤的内容(圖檔+文字)類似RadioButton -->
    <!--android:textAlignment="center" 文本居中-->
    <CheckedTextView
        android:id="@+id/bottomtab_checkedTextView"
        android:tag="tag1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text=""
        android:textSize="@dimen/tab_text_size"
        android:textColor="@color/tab_text_normal"
        android:textAlignment="center"
        />
</RelativeLayout>      

tab_bottom_item

将圖檔資源和selector檔案複制到項目中【後續可根據實際情況更換圖檔】

FragmentTabHostBottomDemo【FragmentTabHost + Fragment實作底部頁籤】
FragmentTabHostBottomDemo【FragmentTabHost + Fragment實作底部頁籤】

在colors.xml檔案中添加以下代碼:【後續可根據實際情況更改背景顔色、文字顔色值】

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <!-- *********************************底部頁籤區域********************************* -->
    <!-- 底部頁籤底部背景色 -->
    <color name="tab_bg_normal">#00000000</color>
    <color name="tab_bg_selected">#00000000</color>
    <!-- 底部頁籤文本顔色 -->
    <color name="tab_text_normal">#8a8a8a</color>
    <color name="tab_text_selected">#38ADFF</color>

</resources>      

在dimens.xml檔案中添加以下代碼:【後續可根據實際情況更改底部頁籤區域的高度值、文字大小值】

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <!-- *********************************底部頁籤區域********************************* -->
    <!--底部頁籤高度值-->
    <dimen name="tab_bottom_background_height">56dp</dimen>
    <!-- 底部頁籤文本大小 -->
    <dimen name="tab_text_size">14sp</dimen>
    <dimen name="tab_medium_text_size">16sp</dimen>
    <dimen name="tab_larger_text_size">18sp</dimen>
    <dimen name="tab_larger_small_text_size">20sp</dimen>

</resources>      

在strings.xml檔案中添加以下代碼:【後續可根據實際情況更改底部頁籤的文字内容】

<resources>
    <string name="app_name">FragmentTabHostBottomDemo</string>

    <!-- *********************************底部頁籤區域********************************* -->
    <string name="home_function_home">首頁</string>
    <string name="home_function_message">消息</string>
    <string name="home_function_contact">我的</string>
</resources>      

至此,頁籤子項的布局所需的檔案已內建到項目中了。

三、使用方法

在Activity布局檔案中引用FragmentTabHost【此Demo采用的是非正常(自己命名的,以便于區分)的布局寫法】

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.why.project.fragmenttabhostbottomdemo.MainActivity">

    <!-- 碎片切換區域 -->
    <FrameLayout
        android:id="@+id/center_layout"
        android:layout_width="match_parent"
        android:layout_height="0.0dp"
        android:layout_weight="1">
    </FrameLayout>

    <!-- 分割線 -->
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#cfcfcf">
    </View>

    <!-- 底部頁籤區域 -->
    <android.support.v4.app.FragmentTabHost
        android:id="@+id/tab_bottom_ftabhost_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <!--
            這個FrameLayout其實是切換區域
            且其id必須為@android:id/tabcontent
        -->
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            />

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

</LinearLayout>      

建立需要用到的fragment類和布局檔案【後續可根據實際情況更改命名,并且需要重新import R檔案】

FragmentTabHostBottomDemo【FragmentTabHost + Fragment實作底部頁籤】
FragmentTabHostBottomDemo【FragmentTabHost + Fragment實作底部頁籤】

特别的是ContactFragment類,用來示範使用FragmentTabHost時,Fragment之間切換時每次都會調用onCreateView方法,導緻每次Fragment的布局都重繪,無法保持Fragment原有狀态。【解開注釋代碼,注釋選中的代碼,會看到不一樣的效果】

package com.why.project.fragmenttabhostbottomdemo.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.why.project.fragmenttabhostbottomdemo.R;


/**
 * Created by HaiyuKing
 * Used 首頁界面——我的碎片界面
 */

public class ContactFragment extends BaseFragment{

    private static final String TAG = "ContactFragment";
    /**View執行個體*/
    private View myView;

    private TextView tv_homef;

    /**傳遞過來的參數*/
    private String bundle_param;

    //重寫
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //使用FragmentTabHost時,Fragment之間切換時每次都會調用onCreateView方法,導緻每次Fragment的布局都重繪,無法保持Fragment原有狀态。
        //http://www.cnblogs.com/changkai244/p/4110173.html
        if(myView==null){
            myView = inflater.inflate(R.layout.fragment_home_contact, container, false);
            //接收傳參
            Bundle bundle = this.getArguments();
            bundle_param = bundle.getString("param");
        }
        //緩存的rootView需要判斷是否已經被加過parent, 如果有parent需要從parent删除,要不然會發生這個rootview已經有parent的錯誤。
        ViewGroup parent = (ViewGroup) myView.getParent();
        if (parent != null) {
            parent.removeView(myView);
        }
        //普通寫法,如果換成這個方式,那麼bundle_param的值不會發生任何變化
//        myView = inflater.inflate(R.layout.fragment_home_contact, container, false);
//        //接收傳參
//        Bundle bundle = this.getArguments();
//        bundle_param = bundle.getString("param");

        return myView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        //初始化控件以及設定
        initView();
        //初始化資料
        initData();
        //初始化控件的點選事件
        initEvent();
    }
    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        tv_homef = (TextView) myView.findViewById(R.id.tv_homef);
    }

    /**
     * 初始化資料
     */
    public void initData() {
        Log.w("tag","{iniData}bundle_param" + bundle_param);
        tv_homef.setText(tv_homef.getText() + "--" + bundle_param);
    }

    /**
     * 初始化點選事件
     * */
    private void initEvent(){
    }

    public void setBundle_param(String bundle_param) {
        this.bundle_param = bundle_param;
    }
}      

在Activity中使用如下【繼承FragmentActivity或者其子類】

package com.why.project.fragmenttabhostbottomdemo;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.Toast;

import com.why.project.fragmenttabhostbottomdemo.fragment.ContactFragment;
import com.why.project.fragmenttabhostbottomdemo.fragment.HomeFragment;
import com.why.project.fragmenttabhostbottomdemo.fragment.MessageFragment;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private FragmentTabHost mBottomFTabHostLayout;

    //頁籤子類集合
    private ArrayList<TabItem> tabItemList = new ArrayList<TabItem>();

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

        initTabList();
        initFTabHostLayout();
        setFTabHostData();
        initEvents();

    }

    /**
     * 初始化頁籤資料集合*/
    private void initTabList() {

        tabItemList.add(new TabItem(this,getResources().getString(R.string.home_function_home),
                R.drawable.home_tab_home_selector,HomeFragment.class));
        tabItemList.add(new TabItem(this,getResources().getString(R.string.home_function_message),
                R.drawable.home_tab_message_selector,MessageFragment.class));
        tabItemList.add(new TabItem(this,getResources().getString(R.string.home_function_contact),
                R.drawable.home_tab_contact_selector,ContactFragment.class));
    }

    /**
     * 初始化FragmentTabHost*/
    private void initFTabHostLayout() {
        //執行個體化
        mBottomFTabHostLayout = (FragmentTabHost) findViewById(R.id.tab_bottom_ftabhost_layout);
        mBottomFTabHostLayout.setup(this, getSupportFragmentManager(), R.id.center_layout);//最後一個參數是碎片切換區域的ID值
        // 去掉分割線
        mBottomFTabHostLayout.getTabWidget().setDividerDrawable(null);

        //設定頁籤區域的自定義寬度和高度
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelSize(R.dimen.tab_bottom_background_height));
        mBottomFTabHostLayout.getTabWidget().setLayoutParams(params);
    }

    /**設定頁籤的内容*/
    private void setFTabHostData() {

        //Tab存在于TabWidget内,而TabWidget是存在于TabHost内。與此同時,在TabHost内無需在寫一個TabWidget,系統已經内置了一個TabWidget
        for (int i = 0; i < tabItemList.size(); i++) {
            //執行個體化一個TabSpec,設定tab的名稱和視圖
            TabHost.TabSpec spec = mBottomFTabHostLayout.newTabSpec(tabItemList.get(i).getTabTitle()).setIndicator(tabItemList.get(i).getTabView());
            // 添加Fragment
            //初始化傳參:http://bbs.csdn.net/topics/391059505
            Bundle bundle = new Bundle();
            bundle.putString("param","初始化傳參");

            mBottomFTabHostLayout.addTab(spec, tabItemList.get(i).getTabFragment(), bundle);

            // 設定Tab按鈕的背景(必須在addTab之後,由于需要子節點(底部菜單按鈕)否則會出現空指針異常)
            mBottomFTabHostLayout.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.tab_bg_selector);
        }

        //預設選中第一項
        mBottomFTabHostLayout.setCurrentTab(0);
        tabItemList.get(0).setChecked(true);
    }

    private void initEvents() {
        //頁籤的切換事件監聽
        mBottomFTabHostLayout.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                //重置Tab樣式
                for (int i = 0; i< tabItemList.size(); i++) {
                    TabItem tabitem = tabItemList.get(i);
                    if (tabId.equals(tabitem.getTabTitle())) {
                        tabitem.setChecked(true);
                    }else {
                        tabitem.setChecked(false);
                    }
                }

                Toast.makeText(MainActivity.this,tabId,Toast.LENGTH_SHORT).show();

                //切換時執行某個Fragment的公共方法,前提是先打開過一次
                //對于更改參數的情況,還需要實作Fragment儲存原有狀态,否則Fragment接收到的始終是初始的bundle的值,因為Fragment之間切換時每次都會調用onCreateView方法。
                int currentTabPosition = mBottomFTabHostLayout.getCurrentTab();
                Fragment fragment = getSupportFragmentManager().findFragmentByTag(tabItemList.get(currentTabPosition).getTabTitle());
                if(fragment instanceof ContactFragment){
                    Log.e("tag","fragment.isDetached()="+fragment.isDetached());
                    if (fragment != null) {
                        ((ContactFragment)fragment).setBundle_param("切換時更改bundle_param的值");
                    }
                }
            }
        });

        //如果想要不切換到相應的fragment,而是打開一個新的界面
        //http://www.jianshu.com/p/3b0ff7a4bde1
        mBottomFTabHostLayout.getTabWidget().getChildTabViewAt(1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"打開一個新的界面",Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 頁籤子項類*/
    class TabItem{

        private Context mContext;

        private CheckedTextView bottomtab_checkedTextView;

        //底部頁籤對應的圖示
        private int tabImgRedId;
        //底部頁籤對應的文字
        private String tabTitle;
        //底部頁籤對應的Fragment類
        private Class<? extends Fragment> tabFragment;

        public TabItem(Context mContext, String tabTitle, int tabImgRedId, Class tabFragment){
            this.mContext = mContext;

            this.tabTitle = tabTitle;
            this.tabImgRedId = tabImgRedId;
            this.tabFragment = tabFragment;
        }

        public Class<? extends Fragment> getTabFragment() {
            return tabFragment;
        }

        public int getTabImgRedId() {
            return tabImgRedId;
        }

        public String getTabTitle() {
            return tabTitle;
        }

        /**
         * 擷取底部頁籤的布局執行個體并初始化設定*/
        private View getTabView() {
            //取得布局執行個體
            View bottomtabitemView = View.inflate(mContext, R.layout.tab_bottom_item, null);

            //===========設定CheckedTextView控件的圖檔和文字==========
            bottomtab_checkedTextView = (CheckedTextView) bottomtabitemView.findViewById(R.id.bottomtab_checkedTextView);

            //設定CheckedTextView控件的android:drawableTop屬性值
            Drawable drawable = ContextCompat.getDrawable(mContext,tabImgRedId);
            //setCompoundDrawables 畫的drawable的寬高是按drawable.setBound()設定的寬高
            //而setCompoundDrawablesWithIntrinsicBounds是畫的drawable的寬高是按drawable固定的寬高,即通過getIntrinsicWidth()與getIntrinsicHeight()自動獲得
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            bottomtab_checkedTextView.setCompoundDrawables(null, drawable, null, null);
            //bottomtab_checkedTextView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);

            //設定CheckedTextView的文字
            bottomtab_checkedTextView.setText(tabTitle.toString());

            return bottomtabitemView;
        }

        /**
         * 更新文字顔色
         */
        public void setChecked(boolean isChecked) {
            if(tabTitle != null){
                if(isChecked){
                    bottomtab_checkedTextView.setTextColor(mContext.getResources().getColor(R.color.tab_text_selected));
                }else{
                    bottomtab_checkedTextView.setTextColor(mContext.getResources().getColor(R.color.tab_text_normal));
                }
            }
        }
    }


}      

混淆配置

參考資料

Android的FragmentTabHost使用(頂部或底部菜單欄)

FragmentTabHost使用方法

Android_ FragmentTabHost切換Fragment時避免重複加載UI

使用FragmentTabHost+TabLayout+ViewPager實作雙層嵌套Tab

如何自定義FragmentTabHost中某一個Tab的點選效果

FragmentTabHost布局的使用及優化方式

改變FragmentTabHost選中的文字顔色

fragmenttabhost 傳參問題

FragmentTabHost+fragment中獲得fragment的對象

fragment中的attach/detach方法說明(網上拷貝,隻為作筆記)

FragmentTabHost切換Fragment,與ViewPager切換Fragment時重新onCreateView的問題

Android頁籤動态滑動效果

項目demo下載下傳位址

https://github.com/haiyuKing/FragmentTabHostBottomDemo