TabWidget是一种控件,通过多种标签来切换显示不同的内容,一个TabWidget主要由一个TabHost来存放多个Tab标签容器,再在Tab容器中加入其它控件,通过addTab方法可以增加新的Tab。这些除了在xml文件中布置好控件外,当然还需要在Java文件中处理好事件的逻辑。
构建TabWidget控件主要需要两个步骤:
1.先写好xml文件
<?xml version="1.0" encoding="utf-8"?>
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#424242"
/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:id="@+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="电影列表:"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="音乐列表:"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/tab3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/view3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="书籍列表:"
/>
</LinearLayout>
</FrameLayout>
</RelativeLayout>
</TabHost>
注意点:TabWidget、FrameLayout的ID必须分别为@android:id/tabs、@android:id/tabcontent
2.在src中写入tabwidget.java
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tabwidget);
TabHost tabs=(TabHost)findViewById(R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec=tabs.newTabSpec("this is 1st tab");
spec.setContent(R.id.view1);
spec.setIndicator("Movie1",getResources().getDrawable(R.drawable.ic_launcher));
tabs.addTab(spec);
spec=tabs.newTabSpec("this is 2st tab");
spec.setContent(R.id.view2);
spec.setIndicator("Music");
tabs.addTab(spec);
spec=tabs.newTabSpec("this is 3st tab");
spec.setContent(R.id.view3);
spec.setIndicator("Book");
tabs.addTab(spec);
tabs.setCurrentTab(0);
运行效果图
问题:
使用spec.setIndicator(“Movie1”,getResources().getDrawable(R.drawable.ic_launcher));加载图片,图片加载不出来?
解决方法:
安卓4.0会有这个问题,修改Manifest.xml里面的Theme,找到System Resources,里面有Theme.black,选这个就行了。
剩下自己要改背景色什么的这个还是比较easy的吧~