【android】使用TabHost+Fragment(替换TabActivity,LocalActivityManager等deprecation类)

时间:2022-07-10 19:30:30

MainActivity

package com.demo.tabfragmenttest;

import android.R.anim;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;

public class MainActivity extends FragmentActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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

tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab1").setContent(R.id.tab1));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("tab2").setContent(R.id.tab2));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}


}


MainActivity对应的layout-activity_main.xml:

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

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

<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>

<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<fragment android:name="com.demo.tabfragmenttest.Tab1Fragment"
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

<fragment android:name="com.demo.tabfragmenttest.Tab2Fragment"
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
</LinearLayout>
</TabHost>



当然,另外你需要建立两个Fragment:Tab1Fragment及Tab2Fragment,这里就省略了。


demo下载:

http://download.csdn.net/detail/xiaodao1986/4504070


免积分通道:

没有积分的朋友可直接联系我QQ:88433062,androidQQ群:33455842