您的位置:首页 > 其它

FragmentTabHostAutoDemo【FragmentTabHost可滑动的选项卡】

2017-11-05 21:46 393 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。

前言

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

效果图

<?xml version="1.0" encoding="utf-8"?>
<!-- 带有下划线的顶部选项卡子项的布局文件(选择图片界面) -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toptabLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="@dimen/tab_top_auto_padding"
android:paddingLeft="@dimen/tab_top_auto_padding"
android:paddingRight="@dimen/tab_top_auto_padding"
>
<!-- 标题 -->
<TextView
android:id="@+id/top_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text=""
android:textSize="@dimen/tab_top_auto_title_size"
android:textColor="@color/tab_text_normal_top"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<!-- 下划线-->
<!-- android:background="@color/tab_underline_selected_top" -->
<TextView
android:id="@+id/top_underline"
android:layout_width="match_parent"
android:layout_height="@dimen/tab_top_auto_height"
android:background="@color/tab_auto_normal_top"
android:layout_below="@id/top_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/tab_top_auto_padding"
/>

</RelativeLayout>


tab_top_auto_item

在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_auto_normal_top">#00ffffff</color>
<color name="tab_auto_selected_top">#3090d9</color>
<!-- 顶部选项卡文本颜色 -->
<color name="tab_text_normal_top">#191919</color>
<color name="tab_text_selected_top">#3090d9</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_top_auto_padding">10dp</dimen>
<!-- 选项卡标题的文字大小 -->
<dimen name="tab_top_auto_title_size">18sp</dimen>
<!-- 选项卡标题的下划线高度 -->
<dimen name="tab_top_auto_height">3dp</dimen>
</resources>


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

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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.why.project.fragmenttabhostautodemo">

<!-- ======================授权访问网络(HttpUtil)========================== -->
<!-- 允许程序打开网络套接字 -->
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

</manifest>


三、使用方法

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

<?xml version="1.0" encoding="utf-8"?>
<!-- 顶部选项卡区域 -->
<com.why.project.fragmenttabhostautodemo.views.tab.MyFragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab_top_auto_ftabhost_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<!-- 必须要有LinearLayout,因为FragmentTabHost属于FrameLayout帧布局 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<!-- 选项卡区域 -->
<!--注意:原来的配置:android:layout_height="?attr/actionBarSize"-->
<TabWidget
android:id="@android:id/tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"/>

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

<!-- 碎片切换区域,且其id必须为@android:id/tabcontent -->
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>

</LinearLayout>

</com.why.project.fragmenttabhostautodemo.views.tab.MyFragmentTabHost>


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





fragment_web.xml文件布局如下

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

<!-- webview -->
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>

</LinearLayout>


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<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() {
//底部选项卡对应的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<? extends Fragment> tabFragment;

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

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

public Class<? extends Fragment> 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));
}
}
}
}
}


混淆配置



参考资料

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/FragmentTabHostAutoDemo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: