Android基础之TabHost

TabHost在日常中的使用很常用,很多市面上的app都或多或少的使用到了tabhost  比如新浪微博客户端,比如最新版的微信5.2,很明显的使用了tabhost


TabHost的使用很简单,按照以下几个步骤,就可以很轻松的做出一个页签效果


1.写一个布局文件 需要有tabhost节点,tabwidget节点 和 显示内容的fragment节点,具体布置如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

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

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#33000000" >
            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >
            </FrameLayout>
        </LinearLayout>
    </TabHost>

</RelativeLayout>

需要强调的是,TabHost  TabWidget Fragment 三个节点的id必须是给定值,不可以随便自定义


2.在java代码中,写一个类继承TabActivity,然后根据xml中的id找到tabhost对象

mTabHost = (TabHost) findViewById(android.R.id.tabhost);
然后根据tabhost对象的几个方法,就可以设置tabhost

public class MainActivity extends TabActivity {

	private TabHost mTabHost;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		initTabHost();
	}

	private void initTabHost() {
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		addTabSpec("conversation", "聊天", R.drawable.tab_conversation,
				new Intent(this, ConversationUI.class));
		addTabSpec("fodler", "发现", R.drawable.tab_folder, new Intent(this,
				FolderUI.class));
		addTabSpec("group", "通讯录", R.drawable.tab_group, new Intent(this,
				GroupUI.class));

	}

	private void addTabSpec(String tag, String label, int icon, Intent intent) {
		//创建tabspec
		TabSpec tabSpec = mTabHost.newTabSpec(tag);
		//创建tab标签和图标
		tabSpec.setIndicator(label, getResources().getDrawable(icon));
		//设置tab页签指定的内容
		tabSpec.setContent(intent);
		
		mTabHost.addTab(tabSpec);
	}
}

效果图如下:



以上步骤可以做出一个最简单的tabhost效果的界面出来,还有很多地方可以自定义,做出效果更好更炫的界面出来,这里就不作介绍了。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

douban.com/note/362236985/
douban.com/note/362237008/
douban.com/note/362237029/
douban.com/note/362237050/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值