当前位置: 移动技术网 > IT编程>移动开发>Android > Android 开发之旅:详解view的几种布局方式及实践

Android 开发之旅:详解view的几种布局方式及实践

2019年07月24日  | 移动技术网IT编程  | 我要评论

产妇用掉百人献血,巧虎迷论坛,极道鲜师电影版国语

引言

我们对android应用程序运行原理及布局文件可谓有了比较深刻的认识和理解,并且用“hello world!”程序来实践证明了。在继续深入android开发之旅之前,有必要解决前两篇中没有介绍的遗留问题:view的几种布局显示方法,以后就不会在针对布局方面做过多的介绍。view的布局显示方式有下面几种:线性布局(linear layout)、相对布局(relative layout)、表格布局(table layout)、网格视图(grid view)、标签布局(tab layout)、列表视图(list view)、绝对布局(absolutelayout)。本文虽然是介绍view的布局方式,但不仅仅是这样,其中涉及了很多小的知识点,绝对能给你带来android大餐!

本文的主要内容就是分别介绍以上视图的七种布局显示方式效果及实现,大纲如下:

1、view布局概述

2、线性布局(linear layout) 

    2.1、tips:android:layout_weight="1"

3、相对布局(relative layout)

4、表格布局(table layout)

5、列表视图(list view) 

    5.1、一个小的改进  

    5.2、补充说明

6、网格视图(grid view)

7 、绝对布局()

8、标签布局(tab layout)

1、view的布局显示概述

通过前面的学习我们知道:在一个android应用程序中,用户界面通过view和viewgroup对象构建。android中有很多种view和viewgroup,他们都继承自view类。view对象是android平台上表示用户界面的基本单元。

view的布局显示方式直接影响用户界面,view的布局方式是指一组view元素如何布局,准确的说是一个viewgroup中包含的一些view怎么样布局。viewgroup类是布局(layout)和视图容器(view container)的基类,此类也定义了viewgroup.layoutparams类,它作为布局参数的基类,此类告诉父视图其中的子视图想如何显示。例如,xml布局文件中名为layout_something的属性(参加上篇的4.2节)。我们要介绍的view的布局方式的类,都是直接或间接继承自viewgroup类,如下图所示:

图1、继承自viewgroup的一些布局类

其实,所有的布局方式都可以归类为viewgroup的5个类别,即viewgroup的5个直接子类。其它的一些布局都扩展自这5个类。下面分小节分别介绍view的七种布局显示方式。

2、线性布局(linear layout)

线性布局:是一个viewgroup以线性方向显示它的子视图(view)元素,即垂直地或水平地。之前我们的hello world!程序中view的布局方式就是线性布局的,一定不陌生!如下所示res/layour/main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       android:orientation="horizontal"><!-- have an eye on ! --> 
  <button android:id="@+id/button1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"      
      android:text="hello, i am a button1" 
      android:layout_weight="1" 
      /> 
  <button android:id="@+id/button2" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:text="hello, i am a button2" 
  android:layout_weight="1" 
  /> 
  <button android:id="@+id/button3" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:text="hello, i am a button3" 
  android:layout_weight="1" 
  /> 
  <button android:id="@+id/button4" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:text="hello, i am a button4" 
  android:layout_weight="1" 
  /> 
  <button android:id="@+id/button5" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:text="hello, i am a button5" 
  android:layout_weight="1" 
  /> 
</linearlayout> 

从上面可以看出根linearlayout视图组(viewgroup)包含5个button,它的子元素是以线性方式(horizontal,水平的)布局,运行效果如下图所示:

图2、线性布局(水平或者说是横向)

如果你在android:orientation="horizontal"设置为vertical,则是是垂直或者说是纵向的,如下图所示:

 图3、线性布局(垂直或者说是纵向)

2.1、tips:android:layout_weight="1"

 这个属性很关键,如果你没有显示设置它,它默认为0。把上面布局文件(水平显示的那个)中的这个属性都去掉,运行会得出如下结果:

图4、layout_weight属性

没有了这个属性,我们本来定义的5个button运行后却只显示了2个button,为什么呢??

"weight"顾名思义是权重的意思,layout_weight 用于给一个线性布局中的诸多视图的重要程度赋值。所有的视图都有一个layout_weight值,默认为零,意思是需要显示多大的视图就占据多大的屏幕空间。这就不难解释为什么会造成上面的情况了:button1~button5都设置了layout_height和layout_width属性为wrap_content即包住文字内容,他们都没有设置layout_weight 属性,即默认为0.,这样button1和button2根据需要的内容占据了整个屏幕,别的就显示不了啦!

若赋一个高于零的值,则将父视图中的可用空间分割,分割大小具体取决于每一个视图的layout_weight值以及该值在当前屏幕布局的整体layout_weight值和在其它视图屏幕布局的layout_weight值中所占的比率而定。举个例子:比如说我们在 水平方向上有一个文本标签和两个文本编辑元素。该文本标签并无指定layout_weight值,所以它将占据需要提供的最少空间。如果两个文本编辑元素每一个的layout_weight值都设置为1,则两者平分在父视图布局剩余的宽度(因为我们声明这两者的重要度相等)。如果两个文本编辑元素其中第一个的layout_weight值设置为1,而第二个的设置为2,则剩余空间的三分之二分给第一个,三分之一分给第二个(数值越小,重要度越高)。 

3、相对布局(relative layout)

相对布局:是一个viewgroup以相对位置显示它的子视图(view)元素,一个视图可以指定相对于它的兄弟视图的位置(例如在给定视图的左边或者下面)或相对于relativelayout的特定区域的位置(例如底部对齐,或中间偏左)。

相对布局是设计用户界面的有力工具,因为它消除了嵌套视图组。如果你发现你使用了多个嵌套的linearlayout视图组后,你可以考虑使用一个relativelayout视图组了。看下面的res/layour/main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent"> 
  <textview 
    android:id="@+id/label" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="type here:"/> 
  <edittext 
    android:id="@+id/entry" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="@android:drawable/editbox_background" 
    android:layout_below="@id/label"/><!-- have an eye on ! --> 
  <button 
    android:id="@+id/ok" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/entry" <!-- have an eye on ! --> 
    android:layout_alignparentright="true" <!-- have an eye on ! --> 
    android:layout_marginleft="10dip" 
    android:text="ok" /> 
  <button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_toleftof="@id/ok" <!-- have an eye on ! --> 
    android:layout_aligntop="@id/ok" <!-- have an eye on ! --> 
    android:text="cancel" /> 
</relativelayout> 

从上面的布局文件我们知道,relativelayout视图组包含一个textview、一个editview、两个button,注意标记了<!-- have an eye on ! -->(请注意运行代码的时候,请把这些注释去掉,否则会运行出错,上面加上是为了更加醒目!)的属性,在使用相对布局方式中就是使用这些类似的属性来定位视图到你想要的位置,它们的值是你参照的视图的id。这些属性的意思很简单,就是英文单词的直译,就不多做介绍了。运行之后,得如下结果:

图5、相对布局

4、 表格布局(table layout)

表格布局:是一个viewgroup以表格显示它的子视图(view)元素,即行和列标识一个视图的位置。其实android的表格布局跟html中的表格布局非常类似,tablerow 就像html表格的<tr>标记。

用表格布局需要知道以下几点:

  • android:shrinkcolumns,对应的方法:setshrinkallcolumns(boolean),作用:设置表格的列是否收缩(列编号从0开始,下同),多列用逗号隔开(下同),如android:shrinkcolumns="0,1,2",即表格的第1、2、3列的内容是收缩的以适合屏幕,不会挤出屏幕。
  • android:collapsecolumns,对应的方法:setcolumncollapsed(int,boolean),作用:设置表格的列是否隐藏
  • android:stretchcolumns,对应的方法:setstretchallcolumns(boolean),作用:设置表格的列是否拉伸

看下面的res/layour/main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<tablelayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       android:shrinkcolumns="0,1,2"><!-- have an eye on ! --> 
  <tablerow><!-- row1 --> 
  <button android:id="@+id/button1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"      
      android:text="hello, i am a button1" 
      android:layout_column="0" 
      /> 
    <button android:id="@+id/button2" 
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:text="hello, i am a button2" 
   android:layout_column="1" 
   /> 
   </tablerow> 
  <tablerow><!-- row2 --> 
  <button android:id="@+id/button3" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"      
      android:text="hello, i am a button3" 
      android:layout_column="1" 
      /> 
<button android:id="@+id/button4" 
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:text="hello, i am a button4" 
   android:layout_column="1" 
   /> 
</tablerow> 
<tablerow>  
   <button android:id="@+id/button5" 
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:text="hello, i am a button5" 
   android:layout_column="2" 
   /> 
</tablerow> 
</tablelayout> 

运行之后可以得出下面的结果:

图6、表格布局

5、列表视图(list view)

列表布局:是一个viewgroup以列表显示它的子视图(view)元素,列表是可滚动的列表。列表元素通过listadapter自动插入到列表。

listadapter:扩展自adapter,它是listview和数据列表之间的桥梁。listview可以显示任何包装在listadapter中的数据。该类提供两个公有类型的抽象方法:

1.public abstract boolean  areallitemsenabled () :表示listadapter中的所有元素是否可激活的?如果返回真,即所有的元素是可选择的即可点击的。

2.public abstract boolean  isenabled (int position) :判断指定位置的元素是否可激活的?

下面通过一个例子来,创建一个可滚动的列表,并从一个字符串数组读取列表元素。当一个元素被选择时,显示该元素在列表中的位置的消息。

1)、首先,将res/layour/main.xml的内容置为如下:

<?xml version="1.0" encoding="utf-8"?> 
<textview xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:padding="10dp" 
  android:textsize="16sp" > 
</textview>

这样就定义了元素在列表中的布局。

2)、src/skynet.com.cnblogs.www/helloworld.java文件的代码如下:

package skynet.com.cnblogs.www;

import android.app.listactivity;
import android.os.bundle;
import android.view.view;
import android.widget.adapterview;
import android.widget.arrayadapter;
import android.widget.listview;
import android.widget.textview;
import android.widget.toast;
import android.widget.adapterview.onitemclicklistener;

public class helloworld extends listactivity {
  //注意这里helloworld类不是扩展自acitvity,而是扩展自listacitivty
  /** called when the activity is first created. */
  @override
  public void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setlistadapter(new arrayadapter<string>(this, r.layout.main, countries));

    listview lv = getlistview();
    lv.settextfilterenabled(true);

    lv.setonitemclicklistener(new onitemclicklistener() {
     public void onitemclick(adapterview<?> parent, view view,
       int position, long id) {
      // when clicked, show a toast with the textview text
      toast.maketext(getapplicationcontext(), ((textview) view).gettext(),
        toast.length_short).show();
     }
    });
  }
  static final string[] countries = new string[] {
   "1", "2", "3", "4", "5",
   "6", "7", "8", "9", "10",
   "11", "12", "13", "14", "15",
   "16", "17", "18", "19", "20",
   "21", "22", "23", "24"
  };
}

note:oncreate()函数中并不像往常一样通过setcontentview()为活动(activity)加载布局文件,替代的是通过setlistadapter(listadapter)自动添加一个listview填充整个屏幕的listactivity。在此文件中这个方法以一个arrayadapter为参数:setlistadapter(new arrayadapter<string>(this, r.layout.main, countries)),这个arrayadapter管理填入listview中的列表元素。arrayadapter的构造函数的参数为:this(表示应用程序的上下文context)、表示listviewde布局文件(这里是r.layout.main)、插入listview的list对象对数组(这里是countres)。

setonitemclicklistener(onitemclicklistener)定义了每个元素的点击(on-click)的监听器,当listview中的元素被点击时,onitemclick()方法被调用,在这里是即一个toast消息——每个元素的位置将显示。

3)、运行应用程序得如下结果(点击1之后,在下面显示了1):

图7、列表布局

note:如果你改了helloworld extends listactivity 而不是activity之后,运行程序是提示:“conversion to dalvik format failed with error 1”。可以这么解决:解决办法是 project > clean... > clean project selected below > ok

5.1、一个小的改进

上面我们是把要填充到listview中的元素硬编码到helloworld.java文件中,这样就缺乏灵活性!也不符合推荐的应用程序的界面与控制它行为的代码更好地分离的准则!

其实我们可以把要填充到listview的元素写到res/values/strings.xml文件中的<string-array>元素中,然后再源码中动态地读取。这样strings.xml的内容类似下面:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string-array name="countries_array">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
    <item>6</item>
    <item>7</item>
  </string-array>
</resources>

然而helloworld.java文件中的oncreate()函数,则这样动态访问这个数组及填充到listvies:

string[] countries = getresources().getstringarray(r.array.countries_array); 
setlistadapter(new arrayadapter<string>(this, r.layout.list_item, countries)); 

5.2、补充说明

首先总结一下列表布局的关键部分:

  • 布局文件中定义listview
  • adapter用来将数据填充到listview
  • 要填充到listview的数据,这些数据可以字符串、图片、控件等等

其中adapter是listview和数据源之间的桥梁,根据数据源的不同adapter可以分为三类:

  • string[]: arrayadapter
  • list<map<string,?>>: simpleadapter
  • 数据库cursor: simplecursoradapter

使用arrayadapter(数组适配器)顾名思义,需要把数据放入一个数组以便显示,上面的例子就是这样的;simpleadapter能定义各种各样的布局出来,可以放上imageview(图片),还可以放上button(按钮),checkbox(复选框)等等;simplecursoradapter是和数据库有关的东西。篇幅有限后面两种就不举例实践了。

6、网格视图(grid view)

网格布局:是一个viewgroup以网格显示它的子视图(view)元素,即二维的、滚动的网格。网格元素通过listadapter自动插入到网格。listadapter跟上面的列表布局是一样的,这里就不重复累述了。

下面也通过一个例子来,创建一个显示图片缩略图的网格。当一个元素被选择时,显示该元素在列表中的位置的消息。

1)、首先,将上面实践截取的图片放入res/drawable/

2)、res/layour/main.xml的内容置为如下:这个gridview填满整个屏幕,而且它的属性都很好理解,按英文单词的意思就对了。

<?xml version="1.0" encoding="utf-8"?>
<gridview xmlns:android="http://schemas.android.com/apk/res/android" 
  android:id="@+id/gridview"
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent"
  android:columnwidth="90dp"
  android:numcolumns="auto_fit"
  android:verticalspacing="10dp"
  android:horizontalspacing="10dp"
  android:stretchmode="columnwidth"
  android:gravity="center"
/>

3)、然后,helloworld.java文件中oncreate()函数如下:

 public void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.main);

    gridview gridview = (gridview) findviewbyid(r.id.gridview);
    gridview.setadapter(new imageadapter(this));

    gridview.setonitemclicklistener(new onitemclicklistener() {
      public void onitemclick(adapterview<?> parent, view v, int position, long id) {
        toast.maketext(helloworld.this, " " + position, toast.length_short).show();
      }
    });
  } 

oncreate()函数跟通常一样,首先调用超类的oncreate()函数函数,然后通过setcontentview()为活动(activity)加载布局文件。紧接着是,通过gridview的id获取布局文件中的gridview,然后调用它的setlistadapter(listadapter)函数填充它,它的参数是一个我们自定义的imageadapter。后面的工作跟列表布局中一样,为监听网格中的元素被点击的事件而做的工作。

4)、实现我们自定义imageadapter,新添加一个类文件,它的代码如下:

package skynet.com.cnblogs.www;

import android.content.context;
import android.view.view;
import android.view.viewgroup;
import android.widget.baseadapter;
import android.widget.gridview;
import android.widget.imageview;

public class imageadapter extends baseadapter {
  private context mcontext;

  public imageadapter(context c) {
    mcontext = c;
  }

  public int getcount() {
    return mthumbids.length;
  }

  public object getitem(int position) {
    return null;
  }

  public long getitemid(int position) {
    return 0;
  }

  // create a new imageview for each item referenced by the adapter
  public view getview(int position, view convertview, viewgroup parent) {
    imageview imageview;
    if (convertview == null) { // if it's not recycled, initialize some attributes
      imageview = new imageview(mcontext);
      imageview.setlayoutparams(new gridview.layoutparams(85, 85));
      imageview.setscaletype(imageview.scaletype.center_crop);
      imageview.setpadding(8, 8, 8, 8);
    } else {
      imageview = (imageview) convertview;
    }

    imageview.setimageresource(mthumbids[position]);
    return imageview;
  }

  // references to our images
  private integer[] mthumbids = {
      r.drawable.linearlayout1, r.drawable.linearlayout2,
      r.drawable.linearlayout3, r.drawable.listview,
      r.drawable.relativelayout, r.drawable.tablelayout
  };
}

imageadapter类扩展自baseadapter,所以首先得实现它所要求必须实现的方法。构造函数和getcount()函数很好理解,而getitem(int)应该返回实际对象在适配器中的特定位置,但是这里我们不需要。类似地,getitemid(int)应该返回元素的行号,但是这里也不需要。

这里重点要介绍的是getview()方法,它为每个要添加到imageadapter的图片都创建了一个新的view。当调用这个方法时,一个view是循环再用的,因此要确认对象是否为空。如果是空的话,一个imageview就被实例化且配置想要的显示属性:

  • setlayoutparams(viewgroup.layoutparams):设置view的高度和宽度,这确保不管drawable中图片的大小,每个图片都被重新设置大小且剪裁以适应这些尺寸。
  • setscaletype(imageview.scaletype):声明图片应该向中心剪裁(如果需要的话)。
  • setpadding(int, int, int, int):定义补距,如果图片有不同的横纵比,小的补距将导致更多的剪裁以适合设置的imageview的高度和宽度。

如果view传到getview()不是空的,则本地的imageview初始化时将循环再用view对象。在getview()方法末尾,position整数传入setimageresource()方法以从mthumbids数组中选择图片。

运行程序会得到如下结果(点击第一张图片之后):

图8、网格布局

7、绝对布局(absolutelayout)

绝对布局:是一个viewgroup以绝对方式显示它的子视图(view)元素,即以坐标的方式来定位在屏幕上位置。

这种布局方式很好理解,在布局文件或编程地设置view的坐标,从而绝对地定位。如下所示布局文件:

<absolutelayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:id="@+id/absolutelayout01" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  >
  <textview android:id="@+id/txtintro"
   android:text="绝对布局"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_x="20dip"<!-- have an eye on ! -->
   android:layout_y="20dip"><!-- have an eye on ! -->
  </textview>
</absolutelayout>

 简单吧,这里不在深入了!

8、标签布局(tab layout)

标签布局:是一个viewgroup以标签的方式显示它的子视图(view)元素,就像在firefox中的一个窗口中显示多个网页一样。

为了狂创建一个标签ui(tabbed ui),需要使用到tabhost和tabwidget。tabhost必须是布局的根节点,它包含为了显示标签的tabwidget和显示标签内容的framelayout。

可以有两种方式实现标签内容:使用标签在同一个活动中交换视图、使用标签在完全隔离的活动之间改变。根据你的需要,选择不同的方式,但是如果每个标签提供不同的用户活动,为每个标签选择隔离的活动,因此你可以更好地以分离的组管理应用程序,而不是一个巨大的应用程序和布局。下面还有一个例子来创建一个标签ui,每个标签使用隔离的活动。

1)、在项目中建立三个隔离的activity类:artistisactivity、albumactivity、songactivity。它们每个表示一个分隔的标签。每个通过textview显示简单的一个消息,例如:

public class artistsactivity extends activity {
  public void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);

    textview textview = new textview(this);
    textview.settext("this is the artists tab");
    setcontentview(textview);
  }
}

其它两个类也类似。

2)、设置每个标签的图标,每个图标应该有两个版本:一个是选中时的,一个是未选中时的。通常的设计建议是,选中的图标应该是深色(灰色),未选中的图标是浅色(白色)。

现在创建一个state-list drawable指定哪个图标表示标签的状态:将图片放到res/drawable目录下并创建一个新的xml文件命名为ic_tab_artists.xml,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <!-- when selected, use grey -->
  <item android:drawable="@drawable/ic_tab_artists_grey"
     android:state_selected="true" />
  <!-- when not selected, use white-->
  <item android:drawable="@drawable/ic_tab_artists_white" />
</selector>

3)、res/layour/main.xml的内容置为如下:

<?xml version="1.0" encoding="utf-8"?>
<tabhost xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/tabhost"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <linearlayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">
    <tabwidget
      android:id="@android:id/tabs"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" />
    <framelayout
      android:id="@android:id/tabcontent"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:padding="5dp" />
  </linearlayout>
</tabhost>

这个布局将显示标签和提供上面创建的活动之间的导航。tabhost要求包含一个tabwidget和一个framelayout。tabwidget和framelayouttabhost以线性垂直地显示。

4)、helloworld.java文件源码如下:

package skynet.com.cnblogs.www;

import android.widget.tabhost;
import android.app.tabactivity;
import android.content.intent;
import android.content.res.resources;
import android.os.bundle;

public class helloworld extends tabactivity{
  /** called when the activity is first created. */
  @override
  public void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.main);

    resources res = getresources(); // resource object to get drawables
    tabhost tabhost = gettabhost(); // the activity tabhost
    tabhost.tabspec spec; // resusable tabspec for each tab
    intent intent; // reusable intent for each tab

    // create an intent to launch an activity for the tab (to be reused)
    intent = new intent().setclass(this, artistsactivity.class);

    // initialize a tabspec for each tab and add it to the tabhost
    spec = tabhost.newtabspec("artists").setindicator("artists",
             res.getdrawable(r.drawable.ic_tab_artists))
           .setcontent(intent);
    tabhost.addtab(spec);

    // do the same for the other tabs
    intent = new intent().setclass(this, albumsactivity.class);
    spec = tabhost.newtabspec("albums").setindicator("albums",
             res.getdrawable(r.drawable.ic_tab_artists))
           .setcontent(intent);
    tabhost.addtab(spec);

    intent = new intent().setclass(this, songsactivity.class);
    spec = tabhost.newtabspec("songs").setindicator("songs",
             res.getdrawable(r.drawable.ic_tab_artists))
           .setcontent(intent);
    tabhost.addtab(spec);

    tabhost.setcurrenttab(2);
  }
}

设置每个标签的文字和图标,并分配每个标签一个活动(这里为了方便三个标签都有相同的图标)。tabhost的引用第一次通过gettabhost()获取。然后,为每个标签,创建tabhost.tabspec定义标签的属性。newtabspec(string)方法创建一个新的tabhost.tabspec以给定的字符串标识标签。调用tabhost.tabspec, setindicator(charsequence, drawable)为每个标签设置文字和图标,调用setcontent(intent)指定intent去打开合适的活动。每个tabhost.tabspec通过调用addtab(tabhost.tabspec)添加到tabhost。

最后,setcurrenttab(int)设置打开默认显示的标签,通过索引标签的位置。

5)、打开android的清单文件androidmanifest.xml,添加notitlebar主题到helloworld的<activity>标记。这将移除默认应用程序的标题和顶端布局,给标签腾出位置。<activity>标记应该像这样:

    <activity android:name=".helloworld"
         android:label="@string/app_name"
         android:theme="@android:style/theme.notitlebar">

你运行这个程序能够得到什么结果呢?请自行检查。不过我在这里告诉你很有可能会运行不了,报“java.lang.nullpointerexception”错!我想运行这个例子的很多人都会有这个问题,不信你试试!

ps:其实这也算是android的一个bug,而且这个bug在2.2中还没有解决,这个问题全球n多人都碰到了,并在中挂号了,相关问题的编号有不止一个。

接着往下看……

如果你看了我这篇文章,你一定会是个幸运儿!经过我艰苦的调试+找资料,我找到了解决方法:

在清单文件androidmanifest.xml,添加下面三个activity:

<activity android:name=".albumsactivity" android:label="@string/app_name"></activity> 
<activity android:name=".artistsactivity" android:label="@string/app_name"></activity> 
<activity android:name=".songsactivity" android:label="@string/app_name"></activity> 

现在运行可以看到如下结果:

图9、标签布局

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网