博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
FragmentTabHostAutoDemo【FragmentTabHost可滑动的选项卡】
阅读量:5871 次
发布时间:2019-06-19

本文共 23819 字,大约阅读时间需要 79 分钟。

版权声明:本文为HaiyuKing原创文章,转载请注明出处!

前言

使用FragmentTabHost实现顶部选项卡(可滑动的效果)展现。

效果图

代码分析

1、该Demo中采用的是FragmentTabHost的布局方案之一【命名为常规布局写法】;

2、使用自定义的FragmentTabHost;

3、实现可滑动效果;

4、设置下划线的宽度和文字的宽度一致;

使用步骤

一、项目组织结构图

注意事项:

1、  导入类文件后需要change包名以及重新import R文件路径

2、  Values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖

二、导入步骤

将自定义的MyFragmentTabHost复制到项目中

package com.why.project.fragmenttabhostautodemo.views.tab;import android.content.Context;import android.content.res.TypedArray;import android.os.Bundle;import android.os.Parcel;import android.os.Parcelable;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.util.AttributeSet;import android.view.View;import android.view.ViewGroup;import android.widget.FrameLayout;import android.widget.LinearLayout;import android.widget.TabHost;import android.widget.TabWidget;import java.util.ArrayList;/** * Created by HaiyuKing * Used 仿照FragmentTabHost并更改doTabChanged方法实现切换Fragment的时候不刷新fragment */public class MyFragmentTabHost extends TabHost        implements TabHost.OnTabChangeListener {    private final ArrayList
mTabs = new ArrayList<>(); private FrameLayout mRealTabContent; private Context mContext; private FragmentManager mFragmentManager; private int mContainerId; private OnTabChangeListener mOnTabChangeListener; private MyFragmentTabHost.TabInfo mLastTab; private boolean mAttached; static final class TabInfo { final @NonNull String tag; final @NonNull Class
clss; final @Nullable Bundle args; Fragment fragment; TabInfo(@NonNull String _tag, @NonNull Class
_class, @Nullable Bundle _args) { tag = _tag; clss = _class; args = _args; } } static class DummyTabFactory implements TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } static class SavedState extends BaseSavedState { String curTab; SavedState(Parcelable superState) { super(superState); } SavedState(Parcel in) { super(in); curTab = in.readString(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(curTab); } @Override public String toString() { return "MyFragmentTabHost.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " curTab=" + curTab + "}"; } public static final Creator
CREATOR = new Creator
() { @Override public MyFragmentTabHost.SavedState createFromParcel(Parcel in) { return new MyFragmentTabHost.SavedState(in); } @Override public MyFragmentTabHost.SavedState[] newArray(int size) { return new MyFragmentTabHost.SavedState[size]; } }; } public MyFragmentTabHost(Context context) { // Note that we call through to the version that takes an AttributeSet, // because the simple Context construct can result in a broken object! super(context, null); initFragmentTabHost(context, null); } public MyFragmentTabHost(Context context, AttributeSet attrs) { super(context, attrs); initFragmentTabHost(context, attrs); } private void initFragmentTabHost(Context context, AttributeSet attrs) { final TypedArray a = context.obtainStyledAttributes(attrs, new int[]{android.R.attr.inflatedId}, 0, 0); mContainerId = a.getResourceId(0, 0); a.recycle(); super.setOnTabChangedListener(this); } private void ensureHierarchy(Context context) { // If owner hasn't made its own view hierarchy, then as a convenience // we will construct a standard one here. if (findViewById(android.R.id.tabs) == null) { LinearLayout ll = new LinearLayout(context); ll.setOrientation(LinearLayout.VERTICAL); addView(ll, new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); TabWidget tw = new TabWidget(context); tw.setId(android.R.id.tabs); tw.setOrientation(TabWidget.HORIZONTAL); ll.addView(tw, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0)); FrameLayout fl = new FrameLayout(context); fl.setId(android.R.id.tabcontent); ll.addView(fl, new LinearLayout.LayoutParams(0, 0, 0)); mRealTabContent = fl = new FrameLayout(context); mRealTabContent.setId(mContainerId); ll.addView(fl, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0, 1)); } } /** * @deprecated Don't call the original TabHost setup, you must instead * call {
@link #setup(Context, FragmentManager)} or * {
@link #setup(Context, FragmentManager, int)}. */ @Override @Deprecated public void setup() { throw new IllegalStateException( "Must call setup() that takes a Context and FragmentManager"); } public void setup(Context context, FragmentManager manager) { ensureHierarchy(context); // Ensure views required by super.setup() super.setup(); mContext = context; mFragmentManager = manager; ensureContent(); } public void setup(Context context, FragmentManager manager, int containerId) { ensureHierarchy(context); // Ensure views required by super.setup() super.setup(); mContext = context; mFragmentManager = manager; mContainerId = containerId; ensureContent(); mRealTabContent.setId(containerId); // We must have an ID to be able to save/restore our state. If // the owner hasn't set one at this point, we will set it ourselves. if (getId() == View.NO_ID) { setId(android.R.id.tabhost); } } private void ensureContent() { if (mRealTabContent == null) { mRealTabContent = (FrameLayout) findViewById(mContainerId); if (mRealTabContent == null) { throw new IllegalStateException( "No tab content FrameLayout found for id " + mContainerId); } } } @Override public void setOnTabChangedListener(OnTabChangeListener l) { mOnTabChangeListener = l; } public void addTab(@NonNull TabSpec tabSpec, @NonNull Class
clss, @Nullable Bundle args) { tabSpec.setContent(new MyFragmentTabHost.DummyTabFactory(mContext)); final String tag = tabSpec.getTag(); final MyFragmentTabHost.TabInfo info = new MyFragmentTabHost.TabInfo(tag, clss, args); if (mAttached) { // If we are already attached to the window, then check to make // sure this tab's fragment is inactive if it exists. This shouldn't // normally happen. info.fragment = mFragmentManager.findFragmentByTag(tag); if (info.fragment != null && !info.fragment.isDetached()) { final FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.detach(info.fragment); ft.commit(); } } mTabs.add(info); addTab(tabSpec); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); final String currentTag = getCurrentTabTag(); // Go through all tabs and make sure their fragments match // the correct state. FragmentTransaction ft = null; for (int i = 0, count = mTabs.size(); i < count; i++) { final MyFragmentTabHost.TabInfo tab = mTabs.get(i); tab.fragment = mFragmentManager.findFragmentByTag(tab.tag); if (tab.fragment != null && !tab.fragment.isDetached()) { if (tab.tag.equals(currentTag)) { // The fragment for this tab is already there and // active, and it is what we really want to have // as the current tab. Nothing to do. mLastTab = tab; } else { // This fragment was restored in the active state, // but is not the current tab. Deactivate it. if (ft == null) { ft = mFragmentManager.beginTransaction(); } ft.detach(tab.fragment); } } } // We are now ready to go. Make sure we are switched to the // correct tab. mAttached = true; ft = doTabChanged(currentTag, ft); if (ft != null) { ft.commit(); mFragmentManager.executePendingTransactions(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mAttached = false; } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); MyFragmentTabHost.SavedState ss = new MyFragmentTabHost.SavedState(superState); ss.curTab = getCurrentTabTag(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof MyFragmentTabHost.SavedState)) { super.onRestoreInstanceState(state); return; } MyFragmentTabHost.SavedState ss = (MyFragmentTabHost.SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setCurrentTabByTag(ss.curTab); } @Override public void onTabChanged(String tabId) { if (mAttached) { final FragmentTransaction ft = doTabChanged(tabId, null); if (ft != null) { ft.commit(); } } if (mOnTabChangeListener != null) { mOnTabChangeListener.onTabChanged(tabId); } } @Nullable private FragmentTransaction doTabChanged(@Nullable String tag, @Nullable FragmentTransaction ft) { final MyFragmentTabHost.TabInfo newTab = getTabInfoForTag(tag); if (mLastTab != newTab) { if (ft == null) { ft = mFragmentManager.beginTransaction(); } if (mLastTab != null) { if (mLastTab.fragment != null) {// ft.detach(mLastTab.fragment); ft.hide(mLastTab.fragment);//http://blog.csdn.net/w1054993544/article/details/37658183 } } if (newTab != null) { if (newTab.fragment == null) { newTab.fragment = Fragment.instantiate(mContext, newTab.clss.getName(), newTab.args); ft.add(mContainerId, newTab.fragment, newTab.tag); } else {// ft.attach(newTab.fragment); ft.show(newTab.fragment);//http://blog.csdn.net/w1054993544/article/details/37658183 } } mLastTab = newTab; } return ft; } @Nullable private MyFragmentTabHost.TabInfo getTabInfoForTag(String tabId) { for (int i = 0, count = mTabs.size(); i < count; i++) { final MyFragmentTabHost.TabInfo tab = mTabs.get(i); if (tab.tag.equals(tabId)) { return tab; } } return null; }}
MyFragmentTabHost

 代码是复制的系统的FragmentTabHost,只有一小部分和系统不一样的代码:

将tab_top_auto_item.xml文件复制到项目中

tab_top_auto_item

在colors.xml文件中添加以下代码:【后续可根据实际情况更改背景颜色、文字颜色值

#3F51B5
#303F9F
#FF4081
#00ffffff
#3090d9
#191919
#3090d9

在dimens.xml文件中添加以下代码:【后续可根据实际情况更改底部选项卡区域的高度值、文字大小值

16dp
16dp
10dp
18sp
3dp

至此,选项卡子项的布局所需的文件已集成到项目中了。

在AndroidManifest.xml文件中添加网络请求的权限【demo中用到的

三、使用方法

在Activity布局文件中引用MyFragmentTabHost【注意:TabWidget的android:layout_width="wrap_content"

创建需要用到的fragment类和布局文件【后续可根据实际情况更改命名,并且需要重新import R文件

 

fragment_web.xml文件布局如下

WebViewFragment

package com.why.project.fragmenttabhostautodemo.fragment;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.webkit.WebView;import android.webkit.WebViewClient;import com.why.project.fragmenttabhostautodemo.R;/** * @Created HaiyuKing * @Used  首页界面——碎片界面 */public class WebViewFragment extends BaseFragment{        private static final String TAG = "WebViewFragment";    /**View实例*/    private View myView;    private WebView web_view;    /**传递过来的参数*/    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_web, 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);        }        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() {        web_view = (WebView) myView.findViewById(R.id.web_view);        //设置支持js脚本//        web_view.getSettings().setJavaScriptEnabled(true);        web_view.setWebViewClient(new WebViewClient() {            /**             * 重写此方法表明点击网页内的链接由自己处理,而不是新开Android的系统browser中响应该链接。             */            @Override            public boolean shouldOverrideUrlLoading(WebView webView, String url) {                //webView.loadUrl(url);                return false;            }        });    }        /**     * 初始化数据     */    public void initData() {        Log.e("tag","{initData}bundle_param="+bundle_param);        web_view.loadUrl(bundle_param);//加载网页    }    /**     * 初始化点击事件     * */    private void initEvent(){    }    }

在Activity中使用如下【继承FragmentActivity或者其子类

package com.why.project.fragmenttabhostautodemo;import android.content.Context;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.FrameLayout;import android.widget.HorizontalScrollView;import android.widget.LinearLayout;import android.widget.RelativeLayout;import android.widget.TabHost;import android.widget.TabWidget;import android.widget.TextView;import android.widget.Toast;import com.why.project.fragmenttabhostautodemo.fragment.WebViewFragment;import com.why.project.fragmenttabhostautodemo.views.tab.MyFragmentTabHost;import java.util.ArrayList;public class MainActivity extends AppCompatActivity {    private MyFragmentTabHost mTopAutoFTabHostLayout;    //选项卡子类集合    private ArrayList
tabItemList = new ArrayList
(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initTabList(); initFTabHostLayout(); setFTabHostData(); initEvents(); } /** * 初始化选项卡数据集合 */ private void initTabList() { //底部选项卡对应的Fragment类使用的是同一个Fragment,那么需要考虑切换Fragment时避免重复加载UI的问题】 tabItemList.add(new TabItem(this,"百度",WebViewFragment.class)); tabItemList.add(new TabItem(this,"CSDN",WebViewFragment.class)); tabItemList.add(new TabItem(this,"博客园",WebViewFragment.class)); tabItemList.add(new TabItem(this,"极客头条",WebViewFragment.class)); tabItemList.add(new TabItem(this,"优设",WebViewFragment.class)); tabItemList.add(new TabItem(this,"玩Android",WebViewFragment.class)); tabItemList.add(new TabItem(this,"掘金",WebViewFragment.class)); } /** * 初始化FragmentTabHost */ private void initFTabHostLayout() { //实例化 mTopAutoFTabHostLayout = (MyFragmentTabHost) findViewById(R.id.tab_top_auto_ftabhost_layout); mTopAutoFTabHostLayout.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);//最后一个参数是碎片切换区域的ID值 // 去掉分割线 mTopAutoFTabHostLayout.getTabWidget().setDividerDrawable(null); } /** * 设置选项卡的内容 */ private void setFTabHostData() { //Tab存在于TabWidget内,而TabWidget是存在于TabHost内。与此同时,在TabHost内无需在写一个TabWidget,系统已经内置了一个TabWidget for (int i = 0; i < tabItemList.size(); i++) { //实例化一个TabSpec,设置tab的名称和视图 TabHost.TabSpec spec = mTopAutoFTabHostLayout.newTabSpec(tabItemList.get(i).getTabTitle()).setIndicator(tabItemList.get(i).getTabView()); // 添加Fragment //初始化传参:http://bbs.csdn.net/topics/391059505 Bundle bundle = new Bundle(); if(i == 0 ){ bundle.putString("param", "http://www.baidu.com"); }else if(i == 1){ bundle.putString("param", "http://blog.csdn.net"); }else if(i == 2){ bundle.putString("param", "http://www.cnblogs.com"); }else if(i == 3){ bundle.putString("param", "http://geek.csdn.net/mobile"); }else if(i == 4){ bundle.putString("param", "http://www.uisdc.com/"); }else if(i == 5){ bundle.putString("param", "http://www.wanandroid.com/index"); }else if(i == 6){ bundle.putString("param", "https://juejin.im/"); } mTopAutoFTabHostLayout.addTab(spec, tabItemList.get(i).getTabFragment(), bundle); } //实现可滑动的选项卡https://stackoverflow.com/questions/14598819/fragmenttabhost-with-horizontal-scroll TabWidget tabWidget = (TabWidget) findViewById(android.R.id.tabs); LinearLayout tabWidgetParent = (LinearLayout) tabWidget.getParent(); HorizontalScrollView hs = new HorizontalScrollView(this); hs.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)); tabWidgetParent.addView(hs, 0); tabWidgetParent.removeView(tabWidget); hs.addView(tabWidget); hs.setHorizontalScrollBarEnabled(false); //默认选中第一项 mTopAutoFTabHostLayout.setCurrentTab(0); tabItemList.get(0).setChecked(true); } private void initEvents() { //选项卡的切换事件监听 mTopAutoFTabHostLayout.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(); } }); } /** * 选项卡子项类*/ class TabItem{ private Context mContext; private TextView top_title; private TextView top_underline; //底部选项卡对应的文字 private String tabTitle; //底部选项卡对应的Fragment类 private Class
tabFragment; public TabItem(Context mContext, String tabTitle, Class tabFragment){ this.mContext = mContext; this.tabTitle = tabTitle; this.tabFragment = tabFragment; } public Class
getTabFragment() { return tabFragment; } public String getTabTitle() { return tabTitle; } /** * 获取底部选项卡的布局实例并初始化设置*/ private View getTabView() { //============引用选项卡的各个选项的布局文件================= View toptabitemView = View.inflate(mContext,R.layout.tab_top_auto_item, null); //===========选项卡的根布局========== RelativeLayout toptabLayout = (RelativeLayout) toptabitemView.findViewById(R.id.toptabLayout); //===========设置选项卡的文字========== top_title = (TextView) toptabitemView.findViewById(R.id.top_title); //设置选项卡的文字 top_title.setText(tabTitle); //===========设置选项卡控件的下划线【不能使用View,否则setWidth不能用】========== top_underline = (TextView) toptabitemView.findViewById(R.id.top_underline); //设置下划线的宽度值==根布局的宽度 top_title.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); Log.w("why", "top_title.getMeasuredWidth()="+top_title.getMeasuredWidth()); toptabLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); Log.w("why", "toptabLayout.getMeasuredWidth()="+toptabLayout.getMeasuredWidth()); top_underline.setWidth(top_title.getMeasuredWidth());//手动设置下划线的宽度值 return toptabitemView; } /** * 更新文字颜色 */ public void setChecked(boolean isChecked) { if(tabTitle != null){ if(isChecked){ //修改文字颜色 top_title.setTextColor(getResources().getColor(R.color.tab_text_selected_top)); //修改下划线的颜色 top_underline.setBackgroundColor(getResources().getColor(R.color.tab_auto_selected_top)); }else{ //修改文字颜色 top_title.setTextColor(getResources().getColor(R.color.tab_text_normal_top)); //修改下划线的颜色 top_underline.setBackgroundColor(getResources().getColor(R.color.tab_auto_normal_top)); } } } }}

混淆配置

参考资料

项目demo下载地址

你可能感兴趣的文章
CDays–4 习题一至四及相关内容解析。
查看>>
L3.十一.匿名函数和map方法
查看>>
前端自动化构建工具webpack (一)之webpack安装 和 设置webpack.confi.js
查看>>
java面向对象高级分层实例_实体类
查看>>
Guice 练习 constructorbindings demo
查看>>
android aapt 用法 -- ApkReader
查看>>
[翻译]用 Puppet 搭建易管理的服务器基础架构(3)
查看>>
Android -- AudioPlayer
查看>>
Python大数据依赖包安装
查看>>
Android View.onMeasure方法的理解
查看>>
Node.js 爬虫初探
查看>>
ABP理论学习之仓储
查看>>
centos7下使用yum安装mysql
查看>>
How can I set ccshared=-fPIC while executing ./configure?
查看>>
2.移植uboot-添加2440单板,并实现NOR、NAND启动
查看>>
hadoop-2.6.5安装
查看>>
vmware虚拟机里的LINUX不能上网的原因一:虚拟网卡设置
查看>>
监控摄像机的区别和分类
查看>>
Java学习——对象和类
查看>>
ElasticSearch 组合过滤器
查看>>