如何在FragmentTabHost添加tab后获取Fragment实例
推荐于2016-11-12 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:117538
获赞数:517193
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。
向TA提问 私信TA
关注
展开全部
//定义FragmentTabHost对象
private MyFragmentTabHost mTabHost;
//定义数组来存放Fragment界面
private Class fragmentArray[] = {BaseFragment.class,BaseFragment.class,BaseFragment.class,BaseFragment.class,BaseFragment.class};
//Tab选项卡的文字
private String mTextviewArray[] = {"a", "b", "c", "d", "e"};
//实例化TabHost对象,得到TabHost
mTabHost = (SunnyFragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
//得到fragment的个数
int count = fragmentArray.length;
for(int i = 0; i < count; i++){
//为每一个Tab按钮设置图标、文字和内容
TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
//将Tab按钮添加进Tab选项卡中
mTabHost.addTab(tabSpec, fragmentArray[i], null);
//设置Fragment的背景
BaseFragment bf = (BaseFragment)getSupportFragmentManager().findFragmentByTag(mTextviewArray[i]);
if(bf!=null)
bf.setBackgroundResource(mBgImgs[i]);
}
其中MyFragmentTabHost参考http://blog.csdn.net/jwzhangjie/article/details/35285779编写,主要是detach和attach部分改为了hide和show
然后在addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args)函数最后增加:
if(info.fragment==null){
info.fragment = Fragment.instantiate(mContext,
info.clss.getName(), info.args);
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.add(mContainerId, info.fragment, info.tag);
ft.hide(info.fragment);
ft.commit();
}
private MyFragmentTabHost mTabHost;
//定义数组来存放Fragment界面
private Class fragmentArray[] = {BaseFragment.class,BaseFragment.class,BaseFragment.class,BaseFragment.class,BaseFragment.class};
//Tab选项卡的文字
private String mTextviewArray[] = {"a", "b", "c", "d", "e"};
//实例化TabHost对象,得到TabHost
mTabHost = (SunnyFragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
//得到fragment的个数
int count = fragmentArray.length;
for(int i = 0; i < count; i++){
//为每一个Tab按钮设置图标、文字和内容
TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
//将Tab按钮添加进Tab选项卡中
mTabHost.addTab(tabSpec, fragmentArray[i], null);
//设置Fragment的背景
BaseFragment bf = (BaseFragment)getSupportFragmentManager().findFragmentByTag(mTextviewArray[i]);
if(bf!=null)
bf.setBackgroundResource(mBgImgs[i]);
}
其中MyFragmentTabHost参考http://blog.csdn.net/jwzhangjie/article/details/35285779编写,主要是detach和attach部分改为了hide和show
然后在addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args)函数最后增加:
if(info.fragment==null){
info.fragment = Fragment.instantiate(mContext,
info.clss.getName(), info.args);
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.add(mContainerId, info.fragment, info.tag);
ft.hide(info.fragment);
ft.commit();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询