Android開發學習筆記:Gallery和GridView淺析

一.Gallery的簡介

Gallery(畫廊)是一個鎖定中心條目並且擁有水平滾動列表的視圖,一般用來瀏覽圖片,並且可以響應事件顯示信息。Gallery還可以和ImageSwitcher組件結合使用來實現一個通過縮略圖來瀏覽圖片的效果。

Gallery常用的XML屬性

屬性名稱

描述

android:animationDuration

設置布局變化時動畫的轉換所需的時間(毫秒級)。僅在動畫開始時計時。該值必須是整數,比如:100。

android:gravity

指定在對象的X和Y軸上如何放置內容。指定一下常量中的一個或多個(使用 「|」分割)

Constant

Value

Description

top

0x30

緊靠容器頂端,不改變其大小

bottom

0x50

緊靠容器底部,不改變其大小

left

0x03

緊靠容器左側,不改變其大小

right

0x05

緊靠容器右側,不改變其大小

center_vertical

0x10

垂直居中,不改變其大小

fill_vertical

0x70

垂直方向上拉伸至充滿容器

center_horizontal

0x01

水平居中,不改變其大小

Fill_horizontal

0x07

水平方向上拉伸使其充滿容器

center

0x11

居中對齊,不改變其大小

fill

0x77

在水平和垂直方向上拉伸,使其充滿容器

clip_vertical

0x80

垂直剪切(當對象邊緣超出容器的時候,將上下邊緣超出的部分剪切掉)

clip_horizontal

0x08

水平剪切(當對象邊緣超出容器的時候,將左右邊緣超出的部分剪切掉)

android:spacing

圖片之間的間距

android:unselectedAlpha

設置未選中的條目的透明度(Alpha)。該值必須是float類型,比如:「1.2」。

首先介紹Gallery單獨使用的例子:

MainActivity.java

  1. packagecom.android.gallerydemo;
  2. importandroid.app.Activity;
  3. importandroid.content.Context;
  4. importandroid.os.Bundle;
  5. importandroid.view.View;
  6. importandroid.view.ViewGroup;
  7. importandroid.widget.AdapterView;
  8. importandroid.widget.AdapterView.OnItemClickListener;
  9. importandroid.widget.BaseAdapter;
  10. importandroid.widget.Gallery;
  11. importandroid.widget.ImageView;
  12. importandroid.widget.Toast;
  13. publicclassMainActivityextendsActivity{
  14. privateGallerygallery;
  15. @Override
  16. publicvoidonCreate(BundlesavedInstanceState){
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.main);
  19. gallery=(Gallery)findViewById(R.id.gallery);
  20. //設置圖片適配器
  21. gallery.setAdapter(newImageAdapter(this));
  22. //設置監聽器
  23. gallery.setOnItemClickListener(newOnItemClickListener(){
  24. @Override
  25. publicvoidonItemClick(AdapterView<?>parent,Viewv,intposition,longid){
  26. Toast.makeText(MainActivity.this,"點擊了第"+(position+1)+"張圖片",Toast.LENGTH_LONG).show();
  27. }
  28. });
  29. }
  30. }
  31. classImageAdapterextendsBaseAdapter{
  32. //聲明Context
  33. privateContextcontext;
  34. //圖片源數組
  35. privateInteger[]imageInteger={
  36. R.drawable.pic1,
  37. R.drawable.pic2,
  38. R.drawable.pic3,
  39. R.drawable.pic4,
  40. R.drawable.pic5,
  41. R.drawable.pic6,
  42. R.drawable.pic7
  43. };
  44. //聲明ImageAdapter
  45. publicImageAdapter(Contextc){
  46. context=c;
  47. }
  48. @Override
  49. //獲取圖片的個數
  50. publicintgetCount(){
  51. returnimageInteger.length;
  52. }
  53. @Override
  54. //獲取圖片在庫中的位置
  55. publicObjectgetItem(intposition){
  56. returnposition;
  57. }
  58. @Override
  59. //獲取圖片在庫中的位置
  60. publiclonggetItemId(intposition){
  61. //TODOAuto-generatedmethodstub
  62. returnposition;
  63. }
  64. @Override
  65. publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
  66. ImageViewimageView=newImageView(context);
  67. //給ImageView設置資源
  68. imageView.setImageResource(imageInteger[position]);
  69. //設置比例類型
  70. imageView.setScaleType(ImageView.ScaleType.FIT_XY);
  71. //設置布局圖片128x192顯示
  72. imageView.setLayoutParams(newGallery.LayoutParams(128,192));
  73. returnimageView;
  74. }
  75. }

main.xml

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <Galleryxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/gallery"
  4. android:layout_width_="fill_parent"
  5. android:layout_height="wrap_content"
  6. android:gravity="center_vertical"
  7. android:background="?android:galleryItemBackground"
  8. />

效果圖:

Gallery和ImageSwitcher組件結合使用的例子:

MainActivity.java

  1. packagecom.android.gallerytest;
  2. importandroid.app.Activity;
  3. importandroid.content.Context;
  4. importandroid.os.Bundle;
  5. importandroid.view.View;
  6. importandroid.view.ViewGroup;
  7. importandroid.view.Window;
  8. importandroid.view.animation.AnimationUtils;
  9. importandroid.widget.AdapterView;
  10. importandroid.widget.BaseAdapter;
  11. importandroid.widget.Gallery;
  12. importandroid.widget.ImageSwitcher;
  13. importandroid.widget.ImageView;
  14. importandroid.widget.AdapterView.OnItemSelectedListener;
  15. importandroid.widget.Gallery.LayoutParams;
  16. importandroid.widget.ViewSwitcher.ViewFactory;
  17. publicclassMainActivityextendsActivityimplementsOnItemSelectedListener,
  18. ViewFactory{
  19. privateImageSwitchermSwitcher;
  20. //大圖片對應的縮略圖源數組
  21. privateInteger[]mThumbIds={R.drawable.sample_thumb_0,
  22. R.drawable.sample_thumb_1,R.drawable.sample_thumb_2,
  23. R.drawable.sample_thumb_3,R.drawable.sample_thumb_4,
  24. R.drawable.sample_thumb_5,R.drawable.sample_thumb_6,
  25. R.drawable.sample_thumb_7};
  26. //大圖片源數組
  27. privateInteger[]mImageIds={R.drawable.sample_0,R.drawable.sample_1,
  28. R.drawable.sample_2,R.drawable.sample_3,R.drawable.sample_4,
  29. R.drawable.sample_5,R.drawable.sample_6,R.drawable.sample_7};
  30. @Override
  31. publicvoidonCreate(BundlesavedInstanceState){
  32. super.onCreate(savedInstanceState);
  33. //設置窗口無標題
  34. requestWindowFeature(Window.FEATURE_NO_TITLE);
  35. setContentView(R.layout.main);
  36. mSwitcher=(ImageSwitcher)findViewById(R.id.switcher);
  37. //注意在使用一個ImageSwitcher之前,
  38. //一定要調用setFactory方法,要不setImageResource這個方法會報空指針異常。
  39. mSwitcher.setFactory(this);
  40. //設置動畫效果
  41. mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
  42. android.R.anim.fade_in));
  43. mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
  44. android.R.anim.fade_out));
  45. Galleryg=(Gallery)findViewById(R.id.gallery);
  46. //添加OnItemSelectedListener監聽器
  47. g.setAdapter(newImageAdapter(this));
  48. g.setOnItemSelectedListener(this);
  49. }
  50. //創建內部類ImageAdapter
  51. publicclassImageAdapterextendsBaseAdapter{
  52. publicImageAdapter(Contextc){
  53. mContext=c;
  54. }
  55. publicintgetCount(){
  56. returnmThumbIds.length;
  57. }
  58. publicObjectgetItem(intposition){
  59. returnposition;
  60. }
  61. publiclonggetItemId(intposition){
  62. returnposition;
  63. }
  64. publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
  65. ImageViewi=newImageView(mContext);
  66. i.setImageResource(mThumbIds[position]);
  67. //設置邊界對齊
  68. i.setAdjustViewBounds(true);
  69. //設置布局參數
  70. i.setLayoutParams(newGallery.LayoutParams(
  71. LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
  72. //設置背景資源
  73. i.setBackgroundResource(R.drawable.picture_frame);
  74. returni;
  75. }
  76. privateContextmContext;
  77. }
  78. @Override
  79. //實現onItemSelected()方法,更換圖片
  80. publicvoidonItemSelected(AdapterView<?>adapter,Viewv,intposition,
  81. longid){
  82. //設置圖片資源
  83. mSwitcher.setImageResource(mImageIds[position]);
  84. }
  85. @Override
  86. publicvoidonNothingSelected(AdapterView<?>arg0){
  87. }
  88. @Override
  89. //實現makeView()方法,為ImageView設置布局格式
  90. publicViewmakeView(){
  91. ImageViewi=newImageView(this);
  92. //設置背景顏色
  93. i.setBackgroundColor(0xFF000000);
  94. //設置比例類型
  95. i.setScaleType(ImageView.ScaleType.FIT_CENTER);
  96. //設置布局參數
  97. i.setLayoutParams(newImageSwitcher.LayoutParams(
  98. LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
  99. returni;
  100. }
  101. }

main.xml

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width_="fill_parent"
  4. android:layout_height="fill_parent"
  5. >
  6. <ImageSwitcher
  7. android:id="@+id/switcher"
  8. android:layout_width_="fill_parent"
  9. android:layout_height="fill_parent"
  10. android:layout_alignParentTop="true"
  11. android:layout_alignParentLeft="true"
  12. />
  13. <Gallery
  14. android:id="@+id/gallery"
  15. android:background="#55000000"
  16. android:layout_width_="fill_parent"
  17. android:layout_height="60dp"
  18. android:layout_alignParentBottom="true"
  19. android:layout_alignParentLeft="true"
  20. android:gravity="center_vertical"
  21. android:spacing="16dp"
  22. />
  23. </RelativeLayout>

效果圖:

二.GridView的簡介

GridView(網格視圖)是按照行列的方式來顯示內容的,一般用於顯示圖片,圖片等內容,比如實現九宮格圖,用GridView是首選,也是最簡單的。主要用於設置Adapter。

GridView常用的XML屬性:

屬性名稱

描述

android:columnWidth

設置列的寬度。

android:gravity

設置此組件中的內容在組件中的位置。可選的值有:top、bottom、left、right、center_vertical、fill_vertical、center_horizontal、fill_horizontal、center、fill、clip_vertical 可以多選,用「|」分開。

android:horizontalSpacing

兩列之間的間距。

android:numColumns

設置列數。

android:stretchMode

縮放模式。

android:verticalSpacing

兩行之間的間距。

下面有三個例子,第一個是只顯示圖片的,第二個是顯示圖片文字的(這裡的圖片是Android系統自帶的圖片),第三個是顯示自定義的圖片文字。前面兩個例子的實現都不是很難,第三個例子的實現有些複雜,學習GridView的時候,就想著能不能自定義自己喜歡的圖片加上文字,在網上找些資料,一般都是第二個例子的形式的,最後在視頻學習上找到了能實現自定義自己的圖片的例子。自己就照著例子去學習,修改成了第三個例子。

第一個例子:

MainActivity.java

  1. package com.android.gridview.activity;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. import android.widget.AdapterView;
  8. import android.widget.AdapterView.OnItemClickListener;
  9. import android.widget.BaseAdapter;
  10. import android.widget.GridView;
  11. import android.widget.ImageView;
  12. import android.widget.Toast;
  13. public class MainActivity extends Activity {
  14. @Override
  15. public void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.main);
  18. GridView gv = (GridView)findViewById(R.id.GridView1);
  19. //為GridView設置適配器
  20. gv.setAdapter(new MyAdapter(this));
  21. //註冊監聽事件
  22. gv.setOnItemClickListener(new OnItemClickListener()
  23. {
  24. public void onItemClick(AdapterView<?> parent, View v, int position, long id)
  25. {
  26. Toast.makeText(MainActivity.this, "pic" + position, Toast.LENGTH_SHORT).show();
  27. }
  28. });
  29. }
  30. }
  31. //自定義適配器
  32. class MyAdapter extends BaseAdapter{
  33. //上下文對象
  34. private Context context;
  35. //圖片數組
  36. private Integer[] imgs = {
  37. R.drawable.pic0, R.drawable.pic1, R.drawable.pic2,
  38. R.drawable.pic3, R.drawable.pic4, R.drawable.pic5,
  39. R.drawable.pic6, R.drawable.pic7, R.drawable.pic8,
  40. R.drawable.pic0, R.drawable.pic1, R.drawable.pic2,
  41. R.drawable.pic3, R.drawable.pic4, R.drawable.pic5,
  42. R.drawable.pic6, R.drawable.pic7, R.drawable.pic8,
  43. };
  44. MyAdapter(Context context){
  45. this.context = context;
  46. }
  47. public int getCount() {
  48. return imgs.length;
  49. }
  50. public Object getItem(int item) {
  51. return item;
  52. }
  53. public long getItemId(int id) {
  54. return id;
  55. }
  56. //創建View方法
  57. public View getView(int position, View convertView, ViewGroup parent) {
  58. ImageView imageView;
  59. if (convertView == null) {
  60. imageView = new ImageView(context);
  61. imageView.setLayoutParams(new GridView.LayoutParams(75, 75));//設置ImageView對象布局
  62. imageView.setAdjustViewBounds(false);//設置邊界對齊
  63. imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);//設置刻度的類型
  64. imageView.setPadding(8, 8, 8, 8);//設置間距
  65. }
  66. else {
  67. imageView = (ImageView) convertView;
  68. }
  69. imageView.setImageResource(imgs[position]);//為ImageView設置圖片資源
  70. return imageView;
  71. }
  72. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width_="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <GridView
  8. android:id="@+id/GridView1"
  9. android:layout_width_="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:columnWidth="90dp"
  12. android:numColumns="3"
  13. android:verticalSpacing="10dp"
  14. android:horizontalSpacing="10dp"
  15. android:stretchMode="columnWidth"
  16. android:gravity="center"
  17. />
  18. </LinearLayout>

效果圖:

第二個例子:

MainActivity.java

  1. package com.android.gridview2.activity;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import android.app.Activity;
  7. import android.os.Bundle;
  8. import android.widget.GridView;
  9. import android.widget.SimpleAdapter;
  10. public class MainActivity extends Activity {
  11. private GridView gv;
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. // TODO Auto-generated method stub
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.gridview);
  17. //準備要添加的數據條目
  18. List<Map<String, Object>> items = new ArrayList<Map<String,Object>>();
  19. for (int i = 0; i < 9; i++) {
  20. Map<String, Object> item = new HashMap<String, Object>();
  21. item.put("imageItem", R.drawable.icon);//添加圖像資源的ID
  22. item.put("textItem", "icon" + i);//按序號添加ItemText
  23. items.add(item);
  24. }
  25. //實例化一個適配器
  26. SimpleAdapter adapter = new SimpleAdapter(this,
  27. items,
  28. R.layout.grid_item,
  29. new String[]{"imageItem", "textItem"},
  30. new int[]{R.id.image_item, R.id.text_item});
  31. //獲得GridView實例
  32. gv = (GridView)findViewById(R.id.mygridview);
  33. //為GridView設置適配器
  34. gv.setAdapter(adapter);
  35. }
  36. }

gridview.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width_="wrap_content"
  4. android:layout_height="wrap_content"
  5. >
  6. <GridView
  7. android:id="@+id/mygridview"
  8. android:numColumns="3"
  9. android:gravity="center_horizontal"
  10. android:layout_width_="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:stretchMode="columnWidth"
  13. />
  14. </LinearLayout>

grid_item.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/RelativeLayout1"
  4. android:layout_width_="wrap_content"
  5. android:layout_height="fill_parent"
  6. android:paddingBottom="6dip"
  7. >
  8. <ImageView
  9. android:id="@+id/image_item"
  10. android:layout_width_="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:layout_centerHorizontal="true"
  13. />
  14. <TextView
  15. android:id="@+id/text_item"
  16. android:layout_below="@+id/image_item"
  17. android:layout_height="wrap_content"
  18. android:layout_width_="wrap_content"
  19. android:layout_centerHorizontal="true"
  20. />
  21. </RelativeLayout>

效果圖:

第三個例子:

MainActivity.java

  1. package com.android.gridview3;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.app.Activity;
  5. import android.content.Context;
  6. import android.os.Bundle;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. import android.widget.AdapterView;
  11. import android.widget.BaseAdapter;
  12. import android.widget.GridView;
  13. import android.widget.ImageView;
  14. import android.widget.TextView;
  15. import android.widget.Toast;
  16. import android.widget.AdapterView.OnItemClickListener;
  17. public class MainActivity extends Activity
  18. {
  19. private GridView gridView;
  20. //圖片的文字標題
  21. private String[] titles = new String[]
  22. { "pic1", "pic2", "pic3", "pic4", "pic5", "pic6", "pic7", "pic8", "pic9"};
  23. //圖片ID數組
  24. private int[] images = new int[]{
  25. R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
  26. R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
  27. R.drawable.pic7, R.drawable.pic8,R.drawable.pic9
  28. };
  29. @Override
  30. public void onCreate(Bundle savedInstanceState){
  31. super.onCreate(savedInstanceState);
  32. setContentView(R.layout.main);
  33. gridView = (GridView) findViewById(R.id.gridview);
  34. PictureAdapter adapter = new PictureAdapter(titles, images, this);
  35. gridView.setAdapter(adapter);
  36. gridView.setOnItemClickListener(new OnItemClickListener()
  37. {
  38. public void onItemClick(AdapterView<?> parent, View v, int position, long id)
  39. {
  40. Toast.makeText(MainActivity.this, "pic" + (position+1), Toast.LENGTH_SHORT).show();
  41. }
  42. });
  43. }
  44. }
  45. //自定義適配器
  46. class PictureAdapter extends BaseAdapter{
  47. private LayoutInflater inflater;
  48. private List<Picture> pictures;
  49. public PictureAdapter(String[] titles, int[] images, Context context)
  50. {
  51. super();
  52. pictures = new ArrayList<Picture>();
  53. inflater = LayoutInflater.from(context);
  54. for (int i = 0; i < images.length; i++)
  55. {
  56. Picture picture = new Picture(titles[i], images[i]);
  57. pictures.add(picture);
  58. }
  59. }
  60. @Override
  61. public int getCount()
  62. {
  63. if (null != pictures)
  64. {
  65. return pictures.size();
  66. } else
  67. {
  68. return 0;
  69. }
  70. }
  71. @Override
  72. public Object getItem(int position)
  73. {
  74. return pictures.get(position);
  75. }
  76. @Override
  77. public long getItemId(int position)
  78. {
  79. return position;
  80. }
  81. @Override
  82. public View getView(int position, View convertView, ViewGroup parent)
  83. {
  84. ViewHolder viewHolder;
  85. if (convertView == null)
  86. {
  87. convertView = inflater.inflate(R.layout.picture_item, null);
  88. viewHolder = new ViewHolder();
  89. viewHolder.title = (TextView) convertView.findViewById(R.id.title);
  90. viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
  91. convertView.setTag(viewHolder);
  92. } else
  93. {
  94. viewHolder = (ViewHolder) convertView.getTag();
  95. }
  96. viewHolder.title.setText(pictures.get(position).getTitle());
  97. viewHolder.image.setImageResource(pictures.get(position).getImageId());
  98. return convertView;
  99. }
  100. }
  101. class ViewHolder
  102. {
  103. public TextView title;
  104. public ImageView image;
  105. }
  106. class Picture
  107. {
  108. private String title;
  109. private int imageId;
  110. public Picture()
  111. {
  112. super();
  113. }
  114. public Picture(String title, int imageId)
  115. {
  116. super();
  117. this.title = title;
  118. this.imageId = imageId;
  119. }
  120. public String getTitle()
  121. {
  122. return title;
  123. }
  124. public void setTitle(String title)
  125. {
  126. this.title = title;
  127. }
  128. public int getImageId()
  129. {
  130. return imageId;
  131. }
  132. public void setImageId(int imageId)
  133. {
  134. this.imageId = imageId;
  135. }
  136. }

main.xml

  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. />

picture_item.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:id="@+id/root"
  5. android:orientation="vertical"
  6. android:layout_width_="wrap_content"
  7. android:layout_height="wrap_content"
  8. android:layout_marginTop="5dp"
  9. >
  10. <ImageView
  11. android:id="@+id/image"
  12. android:layout_width_="100dp"
  13. android:layout_height="150dp"
  14. android:layout_gravity="center"
  15. android:scaleType="fitXY"
  16. android:padding="4dp"
  17. />
  18. <TextView
  19. android:id="@+id/title"
  20. android:layout_width_="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_gravity="center"
  23. android:gravity="center_horizontal"
  24. />
  25. </LinearLayout>

效果圖:

本文出自 「IT的點點滴滴」 博客,請務必保留此出處http://liangruijun.blog.51cto.com/3061169/647355


推薦閱讀:

TAG:學習 | Android | 筆記 | Android開發 | Gallery | View |