TabHost+Fragment分析

总结开发使用tabHost+Fragment的使用步骤:

[b]1、在Activity的布局文件中使用TabHost[/b]

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<!-- Tabwidget的位置决定了tabhost选项卡的位置,移动到父控件的第一个选项卡在上,反之成立 -->
<!-- 这是整个选项卡 -->
<!-- tabStripEnabled选项卡底部没用的部分 -->
<!-- divider 去除选项卡之间的分割线 -->
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#565656"
android:tabStripEnabled="false"
android:divider="@null"
/>

<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />

<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</LinearLayout>
</TabHost>


[b]2、初始化TabHost控件,并找到每一个选项卡[/b]

tabHost = (TabHost) findViewById(android.R.id.tabhost);

TabWidget tw = (TabWidget) ((LinearLayout) tabHost.getChildAt(0))
.getChildAt(TAB_UP);

for(int i = 0 ; i < mTabtexts.length ; i ++){
LinearLayout tab = (LinearLayout) getLayoutInflater().inflate
(R.layout.tab_indicator, tw, false);
((ImageView)tab.getChildAt(0)).setImageResource(mImages[i]);
((TextView)tab.getChildAt(1)).setText(mTabtexts[i]);
mTabs.add(tab);
}

tabHost.setup();//这一步必须有
tabHost.setOnTabChangedListener(changeListener);


[b]3、添加选项卡的内容[/b]

int i = 0 ;
for(LinearLayout tab : mTabs)
tabHost.addTab(tabHost.newTabSpec(mTags[i++])
.setIndicator(tab)
.setContent(new TabContent(this)));


[b]4、然后就是选项卡的切换[/b]

@Override
protected void tabChange(String tabId) {
boy = (BoyFragment) manager.findFragmentByTag(mTags[0]);
girl = (GirlFragment) manager.findFragmentByTag(mTags[1]);

/** FragmentTransaction 在使用之前使用beginTransaction,每一次使用之后需要commit */
transaction = manager.beginTransaction();
detachAll();
toAttach(tabId);
// 使用这个方法提交会有一个问题,当外部调用tabhost.setCurrentTab()时,会报错 */
transaction.commitAllowingStateLoss();
}

private void detachAll(){
if (boy != null)
transaction.detach(boy);
if (girl != null)
transaction.detach(girl);
}


private void toAttach(String tag) {
if(mTags[0].equals(tag)){
if (boy == null) {
transaction.add(R.id.realtabcontent, new BoyFragment(), tag); /** 这里创建Fragment对象,并且绑定tag */
} else {
transaction.attach(boy);
}
}
else if(mTags[1].equals(tag)){
if (girl == null) {
transaction.add(R.id.realtabcontent, new GirlFragment(), tag);
} else {
transaction.attach(girl);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值