版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
【移动应用开发技术】怎么在Android中利用FragmentTabHost实现一个底部菜单功能
怎么在Android中利用FragmentTabHost实现一个底部菜单功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面在下将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。FragmentTabHost简单介绍首先我们看下官方文档的介绍OK,接着官方还给出了一份使用的代码,我们也来看下Activity中使用import
com.example.android.supportv4.R;
import
android.os.Bundle;
import
android.support.v4.app.FragmentActivity;
import
android.support.v4.app.FragmentTabHost;
/**
*
This
demonstrates
how
you
can
implement
switching
between
the
tabs
of
a
*
TabHost
through
fragments,
using
FragmentTabHost.
*/
public
class
FragmentTabs
extends
FragmentActivity
{
private
FragmentTabHost
mTabHost;
@Override
protected
void
onCreate(Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
mTabHost
=
(FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this,
getSupportFragmentManager(),
R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
FragmentStackSupport.CountingFragment.class,
null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
LoaderCursorSupport.CursorLoaderListFragment.class,
null);
mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
LoaderCustomSupport.AppListFragment.class,
null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
LoaderThrottleSupport.ThrottledLoaderListFragment.class,
null);
}
}Fragment中使用import
com.example.android.supportv4.R;
import
android.os.Bundle;
import
android.support.v4.app.Fragment;
import
android.support.v4.app.FragmentTabHost;
import
android.view.LayoutInflater;
import
android.view.View;
import
android.view.ViewGroup;
public
class
FragmentTabsFragmentSupport
extends
Fragment
{
private
FragmentTabHost
mTabHost;
@Override
public
View
onCreateView(LayoutInflater
inflater,
ViewGroup
container,
Bundle
savedInstanceState)
{
mTabHost
=
new
FragmentTabHost(getActivity());
mTabHost.setup(getActivity(),
getChildFragmentManager(),
R.id.fragment1);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
FragmentStackSupport.CountingFragment.class,
null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
LoaderCursorSupport.CursorLoaderListFragment.class,
null);
mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
LoaderCustomSupport.AppListFragment.class,
null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
LoaderThrottleSupport.ThrottledLoaderListFragment.class,
null);
return
mTabHost;
}
@Override
public
void
onDestroyView()
{
super.onDestroyView();
mTabHost
=
null;
}
}FragmentTabHost布局问题官方在给出例子的时候,并没有贴出对应的布局文件,这个布局文件有一些要求,所以我就把我自己写的贴出来吧,方便大家观看<?xml
version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="/apk/res/android"
xmlns:app="/apk/res-auto"
xmlns:tools="/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.study.buttomtabdemo.MainActivity">
<FrameLayout
android:id="@+id/flayout_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<com.study.buttomtabdemo.widget.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
</com.study.buttomtabdemo.widget.FragmentTabHost>
</LinearLayout>这里要注意以下几点:1.我自己自定义了一个FragmentTabHost,因为原来的FragmentTabHost每次切换Fragment事都会走一遍onCreateView()和onResume()方法;2.id必须是android:id=”@android:id/tabhost”这个;3.里面的FrameLayout的id必须是android:id=”@android:id/tabcontent”FragmentTabHost使用下面就到了具体使用的过程了1.定义Tab类因为它属于Tab的一个组合吧,里面包含好多个Tab,所以我们先定义一个Tab类/**
*
主页TAB对应实体
*
Created
by
HFS
on
2017/5/7.
*/
public
class
Tab
{
private
int
title;
//
文字
private
int
icon;
//
图标
private
Class
fragment;
//
对应fragment
public
Tab(Class
fragment,int
title,
int
icon
)
{
this.title
=
title;
this.icon
=
icon;
this.fragment
=
fragment;
}
public
int
getTitle()
{
return
title;
}
public
void
setTitle(int
title)
{
this.title
=
title;
}
public
int
getIcon()
{
return
icon;
}
public
void
setIcon(int
icon)
{
this.icon
=
icon;
}
public
Class
getFragment()
{
return
fragment;
}
public
void
setFragment(Class
fragment)
{
this.fragment
=
fragment;
}
}这里面要对应相应的Fragment,所以需要一个Fragment对象2.初始化Tab集合有几个Tab就往Tab集合添加几个Tab
Tab
tab_home
=
new
Tab(HomeFragment.class,R.string.home,R.drawable.selector_icon_home);
Tab
tab_hot
=
new
Tab(HotFragment.class,R.string.hot,R.drawable.selector_icon_hot);
Tab
tab_category
=
new
Tab(CategoryFragment.class,R.string.catagory,R.drawable.selector_icon_category);
Tab
tab_cart
=
new
Tab(CartFragment.class,R.string.cart,R.drawable.selector_icon_cart);
Tab
tab_mine
=
new
Tab(MineFragment.class,R.string.mine,R.drawable.selector_icon_mine);
mTabs.add(tab_home);
mTabs.add(tab_hot);
mTabs.add(tab_category);
mTabs.add(tab_cart);
mTabs.add(tab_mine);3.setUp找到该控件之后,就要调用对应的这个方法
mInflater
=
LayoutInflater.from(this);
mTabhost
=
(FragmentTabHost)
this.findViewById(android.R.id.tabhost);
mTabhost.setup(this,getSupportFragmentManager(),R.id.flayout_content);4.添加TabSpec到这一步就要添加TabSpec了,有几个Tab,就添加几个TabSpec
for
(Tab
tab
:
mTabs){
TabHost.TabSpec
tabSpec
=
mTabhost.newTabSpec(getString(tab.getTitle()));
tabSpec.setIndicator(buildIndicator(tab));
mTabhost.addTab(tabSpec,tab.getFragment(),null);
}
//构建Indicator
private
View
buildIndicator(Tab
tab){
View
view
=mInflater.inflate(R.layout.tab_indicator,null);
ImageView
img
=
(ImageView)
view.findViewById(R.id.icon_tab);
TextView
text
=
(TextView)
view.findViewById(R.id.txt_indicator);
img.setBackgroundResource(tab.getIcon());
text.setText(tab.getTitle());
return
view;
}5.设置默认显示第一个mTabhost.setCurrentTab(0);6.设置没有分割线mTabhost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);自定义FragmentTabHost类package
com.study.buttomtabdemo.widget;
/**
*
Created
by
monkey
*
on
2014/9/24
*
功能描述:修改过的FragmentTabHost,保存fragment实例不销毁
*/
/*
*
Copyright
(C)
2012
The
Android
Open
Source
Project
*
*
Licensed
under
the
Apache
License,
Version
2.0
(the
"License");
*
you
may
not
use
this
file
except
in
compliance
with
the
License.
*
You
may
obtain
a
copy
of
the
License
at
*
*
/licenses/LICENSE-2.0
*
*
Unless
required
by
applicable
law
or
agreed
to
in
writing,
software
*
distributed
under
the
License
is
distributed
on
an
"AS
IS"
BASIS,
*
WITHOUT
WARRANTIES
OR
CONDITIONS
OF
ANY
KIND,
either
express
or
implied.
*
See
the
License
for
the
specific
language
governing
permissions
and
*
limitations
under
the
License.
*/
import
java.util.ArrayList;
import
android.content.Context;
import
android.content.res.TypedArray;
import
android.os.Bundle;
import
android.os.Parcel;
import
android.os.Parcelable;
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;
/**
*
Special
TabHost
that
allows
the
use
of
{@link
Fragment}
objects
for
its
tab
*
content.
When
placing
this
in
a
view
hierarchy,
after
inflating
the
hierarchy
*
you
must
call
{@link
#setup(Context,
FragmentManager,
int)}
to
complete
the
*
initialization
of
the
tab
host.
*
*
<p>
*
Here
is
a
simple
example
of
using
a
FragmentTabHost
in
an
Activity:
*
*
{@sample
*
development/samples/Support4Demos/src/com/example/android/supportv4/app/
*
FragmentTabs.java
complete}
*
*
<p>
*
This
can
also
be
used
inside
of
a
fragment
through
fragment
nesting:
*
*
{@sample
*
development/samples/Support4Demos/src/com/example/android/supportv4/app/
*
FragmentTabsFragmentSupport.java
complete}
*/
public
class
FragmentTabHost
extends
TabHost
implements
TabHost.OnTabChangeListener
{
private
final
ArrayList<TabInfo>
mTabs
=
new
ArrayList<TabInfo>();
private
FrameLayout
mRealTabContent;
private
Context
mContext;
private
FragmentManager
mFragmentManager;
private
int
mContainerId;
private
OnTabChangeListener
mOnTabChangeListener;
private
TabInfo
mLastTab;
private
boolean
mAttached;
static
final
class
TabInfo
{
private
final
String
tag;
private
final
Class<?>
clss;
private
final
Bundle
args;
private
Fragment
fragment;
TabInfo(String
_tag,
Class<?>
_class,
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);
}
private
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
"FragmentTabHost.SavedState{"
+
Integer.toHexString(System.identityHashCode(this))
+
"
curTab="
+
curTab
+
"}";
}
public
static
final
Creator<SavedState>
CREATOR
=
new
Creator<SavedState>()
{
public
SavedState
createFromParcel(Parcel
in)
{
return
new
SavedState(in);
}
public
SavedState[]
newArray(int
size)
{
return
new
SavedState[size];
}
};
}
public
FragmentTabHost(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
FragmentTabHost(Context
context,
AttributeSet
attrs)
{
super(context,
attrs);
initFragmentTabHost(context,
attrs);
}
private
void
initFragmentTabHost(Context
context,
AttributeSet
attrs)
{
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
ourself.
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(TabSpec
tabSpec,
Class<?>
clss,
Bundle
args)
{
tabSpec.setContent(new
DummyTabFactory(mContext));
String
tag
=
tabSpec.getTag();
TabInfo
info
=
new
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())
{
FragmentTransaction
ft
=
mFragmentManager.beginTransaction();
//
ft.detach(info.fragment);
ft.hide(info.fragment);
mit();
}
}
mTabs.add(info);
addTab(tabSpec);
}
@Override
protected
void
onAttachedToWindow()
{
super.onAttachedToWindow();
String
currentTab
=
getCurrentTabTag();
//
Go
through
all
tabs
and
make
sure
their
fragments
match
//
the
correct
state.
FragmentTransaction
ft
=
null;
for
(int
i
=
0;
i
<
mTabs.size();
i++)
{
TabInfo
tab
=
mTabs.get(i);
tab.fragment
=
mFragmentManager.findFragmentByTag(tab.tag);
//
if
(tab.fragment
!=
null
&&
!tab.fragment.isDetached())
{
if
(tab.fragment
!=
null)
{
if
(tab.tag.equals(currentTab))
{
//
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);
ft.hide(tab.fragment);
}
}
}
//
We
are
now
ready
to
go.
Make
sure
we
are
switched
to
the
//
correct
tab.
mAttached
=
true;
ft
=
doTabChanged(currentTab,
ft);
if
(ft
!=
null)
{
mitAllowingStateLoss();
mFragmentManager.executePendingTransactions();
}
}
@Override
protected
void
onDetachedFromWindow()
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年03月北京市公安局2024年度招考341名文职辅警笔试历年典型题及考点剖析附带答案含详解
- 2024年03月云南省富宁县应急管理局2024年考察调(流)动调进1名工作人员笔试历年典型题及考点剖析附带答案含详解
- 2024年03月中国渔业互保协会2024年公开招考3名工作人员笔试历年典型题及考点剖析附带答案含详解
- 2024年03月中国农业银行四川省分行春季招考聘用380人笔试历年典型题及考点剖析附带答案含详解
- 新活素在男性疾病治疗中的新进展
- G -B- 4789.19-2024 食品安全国家标准 食品微生物学检验 蛋与蛋制品采样和检样处理(正式版)
- 2024年沈阳市自来水营业公司招聘笔试参考题库附带答案详解
- 新版人教版pep小学英语三年级下册期末总复习知识点归纳
- 精细化管理考核标准及评分办法
- 二年级语文下册第2课《找春天》课时练习题(含答案)
- 小升初押题卷:式与方程综合题-六年级下册数学培优卷
- 火区爆破安全技术措施
- 答辩学生汇报情况记录怎么写
- 北京市房山区教师招聘考试真题2022
- 早产儿营养管理课件
- 全初中七年级生物下册考点知识点提分宝典
- 2023高三数学高考冲刺复习备考策略及解题方法技巧指导课件(真题讲解精编)
- 2023年湖南高考理综试卷及答案
- 制氢系统安全要求标准
- 数学建模知到章节答案智慧树2023年湘潭大学
- 高中《生物学》课本中问题参考答案全集(人教2019年版)
评论
0/150
提交评论