Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 334|回复: 0

[默认分类] Android 开发之旅:view的几种布局方式及实践

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-7-12 14:49:02 | 显示全部楼层 |阅读模式
    引言
    通过前面两篇:

    Android 开发之旅:又见Hello World!
    Android 开发之旅:深入分析布局文件&又是“Hello World!”

    我们对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)的基类,此类也定义了
    1. [url=http://androidappdocs.appspot.com/reference/android/view/ViewGroup.LayoutParams.html]ViewGroup.LayoutParams[/url]类,它作为布局参数的基类,此类告诉父视图其中的子视图想如何显示。例如,XML布局文件中名为[b]layout_[i]something[/i][/b]的属性(参加[url=http://www.cnblogs.com/skynet/archive/2010/05/20/1740277.html]上篇的4.2节[/url])。我们要介绍的View的布局方式的类,都是直接或间接继承自[url=http://androidappdocs.appspot.com/reference/android/view/ViewGroup.html]ViewGroup[/url]类,如下图所示:
    复制代码
    1. [url=http://images.cnblogs.com/cnblogs_com/skynet/WindowsLiveWriter/Androidview_11A60/ViewGroup%E7%9A%84%E7%BB%A7%E6%89%BF_2.jpg][img]http://www.itdaan.com/imgs/8/3/2/9/56/72cc7d2b1094d36b11bcaf1b99fefab7.jpe[/img][/url]
    复制代码
    1. 图1、继承自ViewGroup的一些布局类
    复制代码
    1. [/code]其实,所有的布局方式都可以归类为ViewGroup的5个类别,即ViewGroup的5个直接子类。其它的一些布局都扩展自这5个类。下面分小节分别介绍View的七种布局显示方式。
    2. [b]2、线性布局(Linear Layout)[/b]
    3. [b]线性布局[/b]:是一个ViewGroup以线性方向显示它的子视图(view)元素,即[b]垂直地[/b]或[b]水平地[/b]。之前我们的Hello World!程序中view的布局方式就是线性布局的,一定不陌生!如下所示res/layour/main.xml:
    4. <?xml version="1.0" encoding="utf-8"?>
    5. [b]<LinearLayout[/b] xmlns:android="http://schemas.android.com/apk/res/android"
    6.               android:layout_width="fill_parent"
    7.               android:layout_height="fill_parent"
    8.               [b]android:orientation="horizontal"><!-- have an eye on ! -->[/b]
    9.     <Button android:id="@+id/button1"
    10.             android:layout_width="wrap_content"
    11.             android:layout_height="wrap_content"            
    12.             android:text="Hello, I am a Button1"
    13.             android:layout_weight="1"
    14.             />
    15.     <Button android:id="@+id/button2"
    16.     android:layout_width="wrap_content"
    17.     android:layout_height="wrap_content"
    18.     android:text="Hello, I am a Button2"
    19.     android:layout_weight="1"
    20.     />
    21.     <Button android:id="@+id/button3"
    22.     android:layout_width="wrap_content"
    23.     android:layout_height="wrap_content"
    24.     android:text="Hello, I am a Button3"
    25.     android:layout_weight="1"
    26.     />
    27.     <Button android:id="@+id/button4"
    28.     android:layout_width="wrap_content"
    29.     android:layout_height="wrap_content"
    30.     android:text="Hello, I am a Button4"
    31.     android:layout_weight="1"
    32.     />
    33.     <Button android:id="@+id/button5"
    34.     android:layout_width="wrap_content"
    35.     android:layout_height="wrap_content"
    36.     android:text="Hello, I am a Button5"
    37.     android:layout_weight="1"
    38.     />
    39. [b]</LinearLayout>[/b]
    40. 从上面可以看出根LinearLayout视图组(ViewGroup)包含5个Button,它的子元素是以线性方式(horizontal,水平的)布局,运行效果如下图所示:
    41. [url=http://images.cnblogs.com/cnblogs_com/skynet/WindowsLiveWriter/Androidview_11A60/linearlayout1_2.png][img]http://www.itdaan.com/imgs/9/5/6/3/17/804daf0d4fdc30c0ca3f25f318683cf0.jpe[/img][/url]
    42. 图2、线性布局(水平或者说是横向)
    43. 如果你在[b]android:orientation="horizontal"[/b]设置为[b]vertical[/b],则是是垂直或者说是纵向的,如下图所示:
    44. [url=http://images.cnblogs.com/cnblogs_com/skynet/WindowsLiveWriter/Androidview_11A60/linearlayout2_2.png][img]http://www.itdaan.com/imgs/4/4/7/4/72/70a9a8e285f748bdb17a1cdd16dfde7d.jpe[/img][/url]
    45. 图3、线性布局(垂直或者说是纵向)
    46. [b]2.1、Tips:android:layout_weight="1"[/b]
    47. [b] [/b]这个属性很关键,如果你没有显示设置它,它默认为0。把上面布局文件([i]水平显示的那个[/i])中的这个属性都去掉,运行会得出如下结果:
    48. [url=http://images.cnblogs.com/cnblogs_com/skynet/WindowsLiveWriter/Androidview_11A60/linearlayout3_2.png][img]http://www.itdaan.com/imgs/7/4/1/8/11/09a640d4b9979b39681a609d7ce3c171.jpe[/img][/url]
    49. 图4、layout_weight属性
    50. [quote]
    51. [b]没有了这个属性,我们本来定义的5个Button运行后却只显示了2个Button,为什么呢??[/b]
    52. "weight"顾名思义是[b]权重[/b]的意思,layout_weight 用于给一个线性布局中的诸多视图的重要程度赋值。所有的视图都有一个layout_weight值,默认为零,意思是需要显示多大的视图就占据多大的屏幕空间。这就不难解释为什么会造成上面的情况了:Button1~Button5都设置了layout_height和layout_width属性为wrap_content即包住文字内容,他们都没有设置layout_weight 属性,即默认为0.,这样Button1和Button2根据需要的内容占据了整个屏幕,别的就显示不了啦!
    53. 若赋一个高于零的值,则将父视图中的可用空间分割,分割大小具体取决于每一个视图的layout_weight值以及该值在当前屏幕布局的整体layout_weight值和在其它视图屏幕布局的layout_weight值中所占的比率而定。举个例子:比如说我们在 水平方向上有一个文本标签和两个文本编辑元素。该文本标签并无指定layout_weight值,所以它将占据需要提供的最少空间。如果两个文本编辑元素每一个的layout_weight值都设置为1,则两者平分在父视图布局剩余的宽度(因为我们声明这两者的重要度相等)。如果两个文本编辑元素其中第一个的layout_weight值设置为1,而第二个的设置为2,则剩余空间的三分之二分给第一个,三分之一分给第二个([b]数值越小,重要度越高[/b])。  
    54. [/quote]
    55. [b]3、相对布局(Relative Layout)[/b]
    56. [b]相对布局[/b]:是一个ViewGroup以相对位置显示它的子视图(view)元素,一个视图可以指定相对于它的兄弟视图的位置(例如在给定视图的左边或者下面)或相对于[code][url=http://androidappdocs.appspot.com/reference/android/widget/RelativeLayout.html]RelativeLayout[/url]的特定区域的位置(例如底部对齐,或中间偏左)。
    复制代码
    1. 相对布局是设计用户界面的有力工具,因为它消除了嵌套视图组。如果你发现你使用了多个嵌套的[code][url=http://androidappdocs.appspot.com/reference/android/widget/LinearLayout.html]LinearLayout[/url]
    复制代码
    视图组后,你可以考虑使用一个
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/RelativeLayout.html]RelativeLayout[/url]
    复制代码
    视图组了。看下面的res/layour/main.xml:[/code]

    <?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中的表格布局非常类似,
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TableRow.html]TableRow[/url]
    复制代码
    就像HTML表格的<
    1. tr>标记。
    复制代码

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

    android:shrinkColumns,对应的方法:setShrinkAllColumns(boolean),作用:设置表格的列是否收缩(列编号从0开始,下同),多列用逗号隔开(下同),如android:shrinkColumns="0,1,2",即表格的第1、2、3列的内容是收缩的以适合屏幕,不会挤出屏幕。
    android:collapseColumns,对应的方法:setColumnCollapsed(int,boolean),作用:设置表格的列是否隐藏
    android:stretchColumns,对应的方法:setStretchAllColumns(boolean),作用:设置表格的列是否拉伸
    1. 看下面的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)元素,列表是可滚动的列表。列表元素通过
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/ListAdapter.html]ListAdapter[/url]自动插入到列表。
    复制代码
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/ListAdapter.html][b]ListAdapter[/b][/url]
    复制代码
    :扩展自
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/Adapter.html]Adapter[/url]
    复制代码
    ,它是
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/ListView.html]ListView[/url]
    复制代码
    和数据列表之间的桥梁。ListView可以显示任何包装在ListAdapter中的数据。该类提供两个公有类型的抽象方法:

    public abstract boolean  areAllItemsEnabled () :表示ListAdapter中的所有元素是否可激活的?如果返回真,即所有的元素是可选择的即可点击的。
    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文件的代码如下:

    1. package skynet.com.cnblogs.www;
    2. import android.app.ListActivity;
    3. import android.os.Bundle;
    4. import android.view.View;
    5. import android.widget.AdapterView;
    6. import android.widget.ArrayAdapter;
    7. import android.widget.ListView;
    8. import android.widget.TextView;
    9. import android.widget.Toast;
    10. import android.widget.AdapterView.OnItemClickListener;
    11. public class HelloWorld extends [b]ListActivity[/b]  {
    复制代码
    1.     //注意这里Helloworld类不是扩展自Acitvity,而是扩展自ListAcitivty
    2.     /** Called when the activity is first created. */
    3.     @Override
    4.     public void onCreate(Bundle savedInstanceState) {
    5.         super.onCreate(savedInstanceState);
    6.         [b]setListAdapter(new ArrayAdapter<String>(this, R.layout.main, COUNTRIES));[/b]
    7.         ListView lv = getListView();
    8.         lv.setTextFilterEnabled(true);
    9.         lv.setOnItemClickListener(new OnItemClickListener() {
    10.           public void onItemClick(AdapterView<?> parent, View view,
    11.               int position, long id) {
    12.             // When clicked, show a toast with the TextView text
    13.             Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
    14.                 Toast.LENGTH_SHORT).show();
    15.           }
    16.         });
    17.     }
    18.     static final String[] COUNTRIES = new String[] {
    19.             "1", "2", "3", "4", "5",
    20.             "6", "7", "8", "9", "10",
    21.             "11", "12", "13", "14", "15",
    22.             "16", "17", "18", "19", "20",
    23.             "21", "22", "23", "24"
    24.           };
    25. }
    复制代码

    Note:onCreate()函数中并不像往常一样通过setContentView()为活动(Activity)加载布局文件,替代的是通过
    1. [url=http://androidappdocs.appspot.com/reference/android/app/ListActivity.html#setListAdapter%28android.widget.ListAdapter%29]setListAdapter(ListAdapter)[/url]自动添加一个ListView填充整个屏幕的ListActivity。在此文件中这个方法以一个ArrayAdapter为参数:[b]setListAdapter(new ArrayAdapter<String>(this, R.layout.main, COUNTRIES))[/b],这个ArrayAdapter管理填入ListView中的列表元素。ArrayAdapter的构造函数的参数为:this(表示应用程序的上下文context)、表示ListViewde布局文件(这里是R.layout.main)、插入ListView的List对象对数组(这里是COUNTRES)。
    复制代码
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/AdapterView.html#setOnItemClickListener%28android.widget.AdapterView.OnItemClickListener%29]setOnItemClickListener(OnItemClickListener)[/url]定义了每个元素的点击(on-click)的监听器,当ListView中的元素被点击时,[code][url=http://androidappdocs.appspot.com/reference/android/widget/AdapterView.OnItemClickListener.html#onItemClick%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29]onItemClick()[/url]方法被调用,在这里是即一个[code][url=http://androidappdocs.appspot.com/reference/android/widget/Toast.html]Toast[/url]
    复制代码
    消息——每个元素的位置将显示。[/code][/code]
    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的元素写到
    1. res/values/strings.xml
    复制代码
    文件中的
    1. <string-array>
    复制代码
    元素中,然后再源码中动态地读取。这样strings.xml的内容类似下面:

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <resources>
    3.     <string-array name="countries_array">
    4.         <item>1</item>
    5.         <item>2</item>
    6.         <item>3</item>
    7.         <item>4</item>
    8.         <item>5</item>
    9.         <item>6</item>
    10.         <item>7</item>
    11.     </string-array>
    12. </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是和数据库有关的东西。篇幅有限后面两种就不举例实践了。你可以参考android ListView详解orArrayAdapter ,SimpleAdapter ,SimpleCursorAdapter 区别
    6、网格视图(Grid View)
    网格布局:是一个ViewGroup以网格显示它的子视图(view)元素,即二维的、滚动的网格。网格元素通过
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/ListAdapter.html]ListAdapter[/url]自动插入到网格。
    复制代码
    ListAdapter跟上面的列表布局是一样的,这里就不重复累述了。
    下面也通过一个例子来,创建一个显示图片缩略图的网格。当一个元素被选择时,显示该元素在列表中的位置的消息。
    1)、首先,将上面实践截取的图片放入
    1. res/drawable/
    复制代码
    2)、res/layour/main.xml的内容置为如下:这个GridView填满整个屏幕,而且它的属性都很好理解,按英文单词的意思就对了。

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <GridView xmlns:android="http://schemas.android.com/apk/res/android"
    3.     android:id="@+id/gridview"
    4.     android:layout_width="fill_parent"
    5.     android:layout_height="fill_parent"
    6.     android:columnWidth="90dp"
    7.     android:numColumns="auto_fit"
    8.     android:verticalSpacing="10dp"
    9.     android:horizontalSpacing="10dp"
    10.     android:stretchMode="columnWidth"
    11.     android:gravity="center"
    12. />
    复制代码

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

    1.     public void onCreate(Bundle savedInstanceState) {
    2.         super.onCreate(savedInstanceState);
    3.         setContentView(R.layout.main);
    4.         GridView gridview = (GridView) findViewById(R.id.gridview);
    5.         gridview.setAdapter(new ImageAdapter(this));
    6.         gridview.setOnItemClickListener(new OnItemClickListener() {
    7.             public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    8.                 Toast.makeText(HelloWorld.this, " " + position, Toast.LENGTH_SHORT).show();
    9.             }
    10.         });
    11.     }
    复制代码


    onCreate()函数跟通常一样,首先调用超类的onCreate()函数函数,然后通过setContentView()为活动(Activity)加载布局文件。紧接着是,通过GridView的id获取布局文件中的gridview,然后调用它的
    1. [url=http://androidappdocs.appspot.com/reference/android/app/ListActivity.html#setListAdapter%28android.widget.ListAdapter%29]setListAdapter(ListAdapter)[/url]
    复制代码
    函数填充它,它的参数是一个我们自定义的ImageAdapter。后面的工作跟列表布局中一样,为监听网格中的元素被点击的事件而做的工作。
    4)、实现我们自定义ImageAdapter,新添加一个类文件,它的代码如下:

    1. package skynet.com.cnblogs.www;
    2. import android.content.Context;
    3. import android.view.View;
    4. import android.view.ViewGroup;
    5. import android.widget.BaseAdapter;
    6. import android.widget.GridView;
    7. import android.widget.ImageView;
    8. public class ImageAdapter extends BaseAdapter {
    9.     private Context mContext;
    10.     public ImageAdapter(Context c) {
    11.         mContext = c;
    12.     }
    13.     public int getCount() {
    14.         return mThumbIds.length;
    15.     }
    16.     public Object getItem(int position) {
    17.         return null;
    18.     }
    19.     public long getItemId(int position) {
    20.         return 0;
    21.     }
    22.     // create a new ImageView for each item referenced by the Adapter
    23.     public View getView(int position, View convertView, ViewGroup parent) {
    24.         ImageView imageView;
    25.         if (convertView == null) {  // if it"s not recycled, initialize some attributes
    26.             imageView = new ImageView(mContext);
    27.             imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
    28.             imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    29.             imageView.setPadding(8, 8, 8, 8);
    30.         } else {
    31.             imageView = (ImageView) convertView;
    32.         }
    33.         imageView.setImageResource(mThumbIds[position]);
    34.         return imageView;
    35.     }
    36.     // references to our images
    37.     private Integer[] mThumbIds = {
    38.             R.drawable.linearlayout1, R.drawable.linearlayout2,
    39.             R.drawable.linearlayout3, R.drawable.listview,
    40.             R.drawable.relativelayout, R.drawable.tablelayout
    41.     };
    42. }
    复制代码




    ImageAdapter类扩展自
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/BaseAdapter.html]BaseAdapter[/url],所以首先得实现它所要求必须实现的方法。构造函数和getcount()函数很好理解,而getItem(int)应该返回实际对象在适配器中的特定位置,但是这里我们不需要。类似地,getItemId(int)应该返回元素的行号,但是这里也不需要。
    复制代码
    1. 这里重点要介绍的是getView()方法,它为每个要添加到ImageAdapter的图片都创建了一个新的View。当调用这个方法时,一个View是循环再用的,因此要确认对象是否为空。如果是空的话,一个[code][url=http://androidappdocs.appspot.com/reference/android/widget/ImageView.html]ImageView[/url]
    复制代码
    就被实例化且配置想要的显示属性:[/code]

    1. [url=http://androidappdocs.appspot.com/reference/android/view/View.html#setLayoutParams%28android.view.ViewGroup.LayoutParams%29]setLayoutParams(ViewGroup.LayoutParams)[/url]
    复制代码
    :设置View的高度和宽度,这确保不管drawable中图片的大小,每个图片都被重新设置大小且剪裁以适应这些尺寸。
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/ImageView.html#setScaleType%28android.widget.ImageView.ScaleType%29]setScaleType(ImageView.ScaleType)[/url]
    复制代码
    :声明图片应该向中心剪裁(如果需要的话)。
    1. [url=http://androidappdocs.appspot.com/reference/android/view/View.html#setPadding%28int,%20int,%20int,%20int%29]setPadding(int, int, int, int)[/url]
    复制代码
    :定义补距,如果图片有不同的横纵比,小的补距将导致更多的剪裁以适合设置的ImageView的高度和宽度。

    如果View传到getView()不是空的,则本地的ImageView初始化时将循环再用View对象。在getView()方法末尾,position整数传入setImageResource()方法以从mThumbIds数组中选择图片。
    运行程序会得到如下结果(点击第一张图片之后):

    图8、网格布局
    7、绝对布局(AbsoluteLayout)
    绝对布局:是一个ViewGroup以绝对方式显示它的子视图(view)元素,即以坐标的方式来定位在屏幕上位置。
    这种布局方式很好理解,在布局文件或编程地设置View的坐标,从而绝对地定位。如下所示布局文件:

    1. [b]<AbsoluteLayout[/b] xmlns:android="http://schemas.android.com/apk/res/android"
    2.    android:id="@+id/AbsoluteLayout01"
    3.    android:layout_width="fill_parent"
    4.    android:layout_height="fill_parent"
    5.    >
    6.    <TextView android:id="@+id/txtIntro"
    7.      android:text="绝对布局"
    8.      android:layout_width="fill_parent"
    9.      android:layout_height="wrap_content"
    10. [b]     android:layout_x="20dip"<!-- have an eye on ! -->
    11.      android:layout_y="20dip"><!-- have an eye on ! -->[/b]
    12.    </TextView>
    13. [b]</AbsoluteLayout>[/b]
    复制代码


    简单吧,这里不在深入了!
    8、标签布局(Tab Layout)
    标签布局:是一个ViewGroup以标签的方式显示它的子视图(view)元素,就像在Firefox中的一个窗口中显示多个网页一样。
    为了狂创建一个标签UI(tabbed UI),需要使用到
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.html]TabHost[/url]
    复制代码
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabWidget.html]TabWidget[/url]。[code][url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.html]TabHost[/url]
    复制代码
    必须是布局的根节点,它包含为了显示标签的
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabWidget.html]TabWidget[/url]和显示标签内容的[code][url=http://androidappdocs.appspot.com/reference/android/widget/FrameLayout.html]FrameLayout[/url]
    复制代码
    。[/code][/code]
    1. [code]可以有两种方式实现标签内容:使用标签在同一个活动中交换视图、使用标签在完全隔离的活动之间改变。根据你的需要,选择不同的方式,但是如果每个标签提供不同的用户活动,为每个标签选择隔离的活动,因此你可以更好地以分离的组管理应用程序,而不是一个巨大的应用程序和布局。
    复制代码
    [/code]
    1. [code]下面还有一个例子来创建一个标签UI,每个标签使用隔离的活动。
    复制代码
    [/code]
    1)、在项目中建立三个隔离的Activity类:ArtistisActivity、AlbumActivity、SongActivity。它们每个表示一个分隔的标签。每个通过TextView显示简单的一个消息,例如:

    1. public class ArtistsActivity extends Activity {
    2.     public void onCreate(Bundle savedInstanceState) {
    3.         super.onCreate(savedInstanceState);
    4.         TextView textview = new TextView(this);
    5.         textview.setText("This is the Artists tab");
    6.         setContentView(textview);
    7.     }
    8. }
    复制代码


    其它两个类也类似。
    2)、设置每个标签的图标,每个图标应该有两个版本:一个是选中时的,一个是未选中时的。通常的设计建议是,选中的图标应该是深色(灰色),未选中的图标是浅色(白色)。
    现在创建一个state-list drawable指定哪个图标表示标签的状态:将图片放到res/drawable目录下并创建一个新的XML文件命名为
    1. ic_tab_artists.xml
    复制代码
    ,内容如下:

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
    3.     <!-- When selected, use grey -->
    4.     <item android:drawable="@drawable/ic_tab_artists_grey"
    5.           android:state_selected="true" />
    6.     <!-- When not selected, use white-->
    7.     <item android:drawable="@drawable/ic_tab_artists_white" />
    8. </selector>
    复制代码


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

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    3.     android:id="@android:id/tabhost"
    4.     android:layout_width="fill_parent"
    5.     android:layout_height="fill_parent">
    6.     <LinearLayout
    7.         android:orientation="vertical"
    8.         android:layout_width="fill_parent"
    9.         android:layout_height="fill_parent"
    10.         android:padding="5dp">
    11.         <TabWidget
    12.             android:id="@android:id/tabs"
    13.             android:layout_width="fill_parent"
    14.             android:layout_height="wrap_content" />
    15.         <FrameLayout
    16.             android:id="@android:id/tabcontent"
    17.             android:layout_width="fill_parent"
    18.             android:layout_height="fill_parent"
    19.             android:padding="5dp" />
    20.     </LinearLayout>
    21. </TabHost>
    复制代码


    这个布局将显示标签和提供上面创建的活动之间的导航。
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.html]TabHost[/url]
    复制代码
    1. 要求包含一个[url=http://androidappdocs.appspot.com/reference/android/widget/TabWidget.html]TabWidget[/url]和一个[code][url=http://androidappdocs.appspot.com/reference/android/widget/FrameLayout.html]FrameLayout[/url]
    复制代码
    TabWidget
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/FrameLayout.html]FrameLayout[/url]
    复制代码
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.html]TabHost[/url]
    复制代码
    以线性垂直地显示。[/code]
    4)、HelloWorld.java文件源码如下:

    1. package skynet.com.cnblogs.www;
    2. import android.widget.TabHost;
    3. import android.app.TabActivity;
    4. import android.content.Intent;
    5. import android.content.res.Resources;
    6. import android.os.Bundle;
    7. public class HelloWorld extends TabActivity{
    8.     /** Called when the activity is first created. */
    9.     @Override
    10.     public void onCreate(Bundle savedInstanceState) {
    11.         super.onCreate(savedInstanceState);
    12.         setContentView(R.layout.main);
    13.         Resources res = getResources(); // Resource object to get Drawables
    14.         TabHost tabHost = getTabHost();  // The activity TabHost
    15.         TabHost.TabSpec spec;  // Resusable TabSpec for each tab
    16.         Intent intent;  // Reusable Intent for each tab
    17.         // Create an Intent to launch an Activity for the tab (to be reused)
    18.         intent = new Intent().setClass(this, ArtistsActivity.class);
    19.         // Initialize a TabSpec for each tab and add it to the TabHost
    20.         spec = tabHost.newTabSpec("artists").setIndicator("Artists",
    21.                           res.getDrawable(R.drawable.ic_tab_artists))
    22.                       .setContent(intent);
    23.         tabHost.addTab(spec);
    24.         // Do the same for the other tabs
    25.         intent = new Intent().setClass(this, AlbumsActivity.class);
    26.         spec = tabHost.newTabSpec("albums").setIndicator("Albums",
    27.                           res.getDrawable(R.drawable.ic_tab_artists))
    28.                       .setContent(intent);
    29.         tabHost.addTab(spec);
    30.         intent = new Intent().setClass(this, SongsActivity.class);
    31.         spec = tabHost.newTabSpec("songs").setIndicator("Songs",
    32.                           res.getDrawable(R.drawable.ic_tab_artists))
    33.                       .setContent(intent);
    34.         tabHost.addTab(spec);
    35.         tabHost.setCurrentTab(2);
    36.     }
    37. }
    复制代码




    设置每个标签的文字和图标,并分配每个标签一个活动(这里为了方便三个标签都有相同的图标)。TabHost的引用第一次通过
    1. [url=http://androidappdocs.appspot.com/reference/android/app/TabActivity.html#getTabHost%28%29]getTabHost()[/url]获取。然后,为每个标签,创建[code][url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.TabSpec.html]TabHost.TabSpec[/url]定义标签的属性。[code][url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.html#newTabSpec%28java.lang.String%29]newTabSpec(String)[/url]
    复制代码
    方法创建一个新的
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.TabSpec.html]TabHost.TabSpec[/url]
    复制代码
    以给定的字符串标识标签。调用
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.TabSpec.html]TabHost.TabSpec[/url]
    复制代码
    ,
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.TabSpec.html#setIndicator%28java.lang.CharSequence,%20android.graphics.drawable.Drawable%29]setIndicator(CharSequence, Drawable)[/url]
    复制代码
    为每个标签设置文字和图标,调用
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.TabSpec.html#setContent%28android.content.Intent%29]setContent(Intent)[/url]
    复制代码
    指定
    1. [url=http://androidappdocs.appspot.com/reference/android/content/Intent.html]Intent[/url]
    复制代码
    去打开合适的活动。每个
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.TabSpec.html]TabHost.TabSpec[/url]
    复制代码
    通过调用
    1. [url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.html#addTab%28android.widget.TabHost.TabSpec%29]addTab(TabHost.TabSpec)[/url]添加到TabHost。
    复制代码
    [/code][/code]
    1. [code][code]最后,[code][url=http://androidappdocs.appspot.com/reference/android/widget/TabHost.html#setCurrentTab%28int%29]setCurrentTab(int)[/url]
    复制代码
    设置打开默认显示的标签,通过索引标签的位置。[/code][/code][/code]
    5)、打开Android的清单文件AndroidManifest.xml,添加
    1. NoTitleBar主题到HelloWorld的[code]<activity>标记。这将移除默认应用程序的标题和顶端布局,给标签腾出位置。[code]<activity>
    复制代码
    标记应该像这样:[/code][/code]

    1.         <activity android:name=".HelloWorld"
    2.                   android:label="@string/app_name"
    3.                   android:theme="@android:style/Theme.NoTitleBar">
    复制代码

    1. [code]你运行这个程序能够得到什么结果呢?请自行检查。不过我在这里告诉你很有可能会运行不了,报“java.lang.NullPointerException”错!我想运行这个例子的很多人都会有这个问题,不信你试试!
    复制代码
    [/code]
    1. [code]PS:其实这也算是Android的一个bug,而且这个bug在2.2中还没有解决,这个问题全球N多人都碰到了,并在[url=http://code.google.com/p/android/issues]http://code.google.com/p/android/issues[/url]中挂号了,相关问题的编号有不止一个。
    复制代码
    [/code]
    1. [code]
    复制代码
    [/code]
    1. [code]接着往下看……
    复制代码
    [/code]
    1. [code]如果你看了我这篇文章,你一定会是个幸运儿!经过我艰苦的调试+找资料,我找到了解决方法:
    复制代码
    [/code]
    1. [code]在清单文件AndroidManifest.xml,添加下面三个Activity:
    复制代码
    [/code]

    <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、标签布局
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-20 06:32 , Processed in 0.447052 second(s), 50 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表