选项卡在android也是一个很常用的组件,网页里就更不用说了,到处俯拾皆是。今天呢也抽空学习了一下觉得还是挺简单的就准备发个文章记录一下。
1.生成选项卡在android一般有2种方法一种是继承TabActivity,一种就是直接写配置文件。最方便的是第一种方法了。
2.编写配置文件,这里就弄3个选项卡,每个选项卡只是一个TextView.这个配置文件我写在一个单独的xml文件里
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="第一个选项卡"
/>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab2"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="第二个选项卡"
/>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab3"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="第三个选项卡"
/>
</LinearLayout>
</LinearLayout>
3.使用activity实现选项卡的功能
(1)首先让我们的activity继承TabActivity,需要注意的是activity的名称不能是TabActivity
(2)使用LayoutInflater进行布局转换
(3)循环取出布局标记
(4)定义tablespec、标签文字、标签显示的组件
代码如下所示
package org.lxh.activity;
import android.app.Activity;
import android.app.TabActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class MyTabActivity extends TabActivity {
//定义TabHost
private TabHost tabHost;
//定义内嵌布局管理器ID
private int[] ids={R.id.tab1,R.id.tab2,R.id.tab3};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
//取得TabHost对象
tabHost=super.getTabHost();
//布局转化
LayoutInflater.from(this).inflate(R.layout.tab, this.tabHost.getTabContentView(), true);
//循环取出所有的布局标记
for(int i=0;i<ids.length;i++){
TabSpec spec=tabHost.newTabSpec("tab"+i);
//设置标签文字
spec.setIndicator("选项卡"+i);
//设置显示的组件
spec.setContent(ids[i]);
//添加tab
tabHost.addTab(spec);
}
}
}
下面看下运行效果
到这里程序也就写好了,这次我运行程序出现了一个这样的错误
运行时出现的错误Re-installation failed due to different application signatures,没法启动时,
调试信息如下:
[2013-02-02 10:08:37 - ApiDemos] Re-installation failed due to different application signatures.
[2013-02-02 10:08:37 - ApiDemos] You must perform a full uninstall of the application. WARNING:
[2013-02-02 10:08:37 - ApiDemos] Please execute 'adb uninstall org.lxh.MyTabActivity' in a
[2013-02-02 10:08:37 - ApiDemos] Launch canceled!
解决方法就是进入SDK的tools目录,执行如下命令就OK了。