Android開發學習筆記:Gallery和GridView淺析
一.Gallery的簡介
Gallery(畫廊)是一個鎖定中心條目並且擁有水平滾動列表的視圖,一般用來瀏覽圖片,並且可以響應事件顯示信息。Gallery還可以和ImageSwitcher組件結合使用來實現一個通過縮略圖來瀏覽圖片的效果。
Gallery常用的XML屬性
屬性名稱 |
描述 |
|||||||||||||||||||||||||||||||||||||||
android:animationDuration |
設置布局變化時動畫的轉換所需的時間(毫秒級)。僅在動畫開始時計時。該值必須是整數,比如:100。 |
|||||||||||||||||||||||||||||||||||||||
android:gravity |
指定在對象的X和Y軸上如何放置內容。指定一下常量中的一個或多個(使用 「|」分割)
|
|||||||||||||||||||||||||||||||||||||||
android:spacing |
圖片之間的間距 |
|||||||||||||||||||||||||||||||||||||||
android:unselectedAlpha |
設置未選中的條目的透明度(Alpha)。該值必須是float類型,比如:「1.2」。 |
首先介紹Gallery單獨使用的例子:
MainActivity.java
- packagecom.android.gallerydemo;
- importandroid.app.Activity;
- importandroid.content.Context;
- importandroid.os.Bundle;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- importandroid.widget.AdapterView;
- importandroid.widget.AdapterView.OnItemClickListener;
- importandroid.widget.BaseAdapter;
- importandroid.widget.Gallery;
- importandroid.widget.ImageView;
- importandroid.widget.Toast;
- publicclassMainActivityextendsActivity{
- privateGallerygallery;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- gallery=(Gallery)findViewById(R.id.gallery);
- //設置圖片適配器
- gallery.setAdapter(newImageAdapter(this));
- //設置監聽器
- gallery.setOnItemClickListener(newOnItemClickListener(){
- @Override
- publicvoidonItemClick(AdapterView<?>parent,Viewv,intposition,longid){
- Toast.makeText(MainActivity.this,"點擊了第"+(position+1)+"張圖片",Toast.LENGTH_LONG).show();
- }
- });
- }
- }
- classImageAdapterextendsBaseAdapter{
- //聲明Context
- privateContextcontext;
- //圖片源數組
- privateInteger[]imageInteger={
- R.drawable.pic1,
- R.drawable.pic2,
- R.drawable.pic3,
- R.drawable.pic4,
- R.drawable.pic5,
- R.drawable.pic6,
- R.drawable.pic7
- };
- //聲明ImageAdapter
- publicImageAdapter(Contextc){
- context=c;
- }
- @Override
- //獲取圖片的個數
- publicintgetCount(){
- returnimageInteger.length;
- }
- @Override
- //獲取圖片在庫中的位置
- publicObjectgetItem(intposition){
- returnposition;
- }
- @Override
- //獲取圖片在庫中的位置
- publiclonggetItemId(intposition){
- //TODOAuto-generatedmethodstub
- returnposition;
- }
- @Override
- publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
- ImageViewimageView=newImageView(context);
- //給ImageView設置資源
- imageView.setImageResource(imageInteger[position]);
- //設置比例類型
- imageView.setScaleType(ImageView.ScaleType.FIT_XY);
- //設置布局圖片128x192顯示
- imageView.setLayoutParams(newGallery.LayoutParams(128,192));
- returnimageView;
- }
- }
main.xml
- <?xmlversion="1.0"encoding="utf-8"?>
- <Galleryxmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/gallery"
- android:layout_width_="fill_parent"
- android:layout_height="wrap_content"
- android:gravity="center_vertical"
- android:background="?android:galleryItemBackground"
- />
效果圖:
Gallery和ImageSwitcher組件結合使用的例子:
MainActivity.java
- packagecom.android.gallerytest;
- importandroid.app.Activity;
- importandroid.content.Context;
- importandroid.os.Bundle;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- importandroid.view.Window;
- importandroid.view.animation.AnimationUtils;
- importandroid.widget.AdapterView;
- importandroid.widget.BaseAdapter;
- importandroid.widget.Gallery;
- importandroid.widget.ImageSwitcher;
- importandroid.widget.ImageView;
- importandroid.widget.AdapterView.OnItemSelectedListener;
- importandroid.widget.Gallery.LayoutParams;
- importandroid.widget.ViewSwitcher.ViewFactory;
- publicclassMainActivityextendsActivityimplementsOnItemSelectedListener,
- ViewFactory{
- privateImageSwitchermSwitcher;
- //大圖片對應的縮略圖源數組
- privateInteger[]mThumbIds={R.drawable.sample_thumb_0,
- R.drawable.sample_thumb_1,R.drawable.sample_thumb_2,
- R.drawable.sample_thumb_3,R.drawable.sample_thumb_4,
- R.drawable.sample_thumb_5,R.drawable.sample_thumb_6,
- R.drawable.sample_thumb_7};
- //大圖片源數組
- privateInteger[]mImageIds={R.drawable.sample_0,R.drawable.sample_1,
- R.drawable.sample_2,R.drawable.sample_3,R.drawable.sample_4,
- R.drawable.sample_5,R.drawable.sample_6,R.drawable.sample_7};
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- //設置窗口無標題
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.main);
- mSwitcher=(ImageSwitcher)findViewById(R.id.switcher);
- //注意在使用一個ImageSwitcher之前,
- //一定要調用setFactory方法,要不setImageResource這個方法會報空指針異常。
- mSwitcher.setFactory(this);
- //設置動畫效果
- mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
- android.R.anim.fade_in));
- mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
- android.R.anim.fade_out));
- Galleryg=(Gallery)findViewById(R.id.gallery);
- //添加OnItemSelectedListener監聽器
- g.setAdapter(newImageAdapter(this));
- g.setOnItemSelectedListener(this);
- }
- //創建內部類ImageAdapter
- publicclassImageAdapterextendsBaseAdapter{
- publicImageAdapter(Contextc){
- mContext=c;
- }
- publicintgetCount(){
- returnmThumbIds.length;
- }
- publicObjectgetItem(intposition){
- returnposition;
- }
- publiclonggetItemId(intposition){
- returnposition;
- }
- publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
- ImageViewi=newImageView(mContext);
- i.setImageResource(mThumbIds[position]);
- //設置邊界對齊
- i.setAdjustViewBounds(true);
- //設置布局參數
- i.setLayoutParams(newGallery.LayoutParams(
- LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
- //設置背景資源
- i.setBackgroundResource(R.drawable.picture_frame);
- returni;
- }
- privateContextmContext;
- }
- @Override
- //實現onItemSelected()方法,更換圖片
- publicvoidonItemSelected(AdapterView<?>adapter,Viewv,intposition,
- longid){
- //設置圖片資源
- mSwitcher.setImageResource(mImageIds[position]);
- }
- @Override
- publicvoidonNothingSelected(AdapterView<?>arg0){
- }
- @Override
- //實現makeView()方法,為ImageView設置布局格式
- publicViewmakeView(){
- ImageViewi=newImageView(this);
- //設置背景顏色
- i.setBackgroundColor(0xFF000000);
- //設置比例類型
- i.setScaleType(ImageView.ScaleType.FIT_CENTER);
- //設置布局參數
- i.setLayoutParams(newImageSwitcher.LayoutParams(
- LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
- returni;
- }
- }
main.xml
- <?xmlversion="1.0"encoding="utf-8"?>
- <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width_="fill_parent"
- android:layout_height="fill_parent"
- >
- <ImageSwitcher
- android:id="@+id/switcher"
- android:layout_width_="fill_parent"
- android:layout_height="fill_parent"
- android:layout_alignParentTop="true"
- android:layout_alignParentLeft="true"
- />
- <Gallery
- android:id="@+id/gallery"
- android:background="#55000000"
- android:layout_width_="fill_parent"
- android:layout_height="60dp"
- android:layout_alignParentBottom="true"
- android:layout_alignParentLeft="true"
- android:gravity="center_vertical"
- android:spacing="16dp"
- />
- </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
- package com.android.gridview.activity;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemClickListener;
- import android.widget.BaseAdapter;
- import android.widget.GridView;
- import android.widget.ImageView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- GridView gv = (GridView)findViewById(R.id.GridView1);
- //為GridView設置適配器
- gv.setAdapter(new MyAdapter(this));
- //註冊監聽事件
- gv.setOnItemClickListener(new OnItemClickListener()
- {
- public void onItemClick(AdapterView<?> parent, View v, int position, long id)
- {
- Toast.makeText(MainActivity.this, "pic" + position, Toast.LENGTH_SHORT).show();
- }
- });
- }
- }
- //自定義適配器
- class MyAdapter extends BaseAdapter{
- //上下文對象
- private Context context;
- //圖片數組
- private Integer[] imgs = {
- R.drawable.pic0, R.drawable.pic1, R.drawable.pic2,
- R.drawable.pic3, R.drawable.pic4, R.drawable.pic5,
- R.drawable.pic6, R.drawable.pic7, R.drawable.pic8,
- R.drawable.pic0, R.drawable.pic1, R.drawable.pic2,
- R.drawable.pic3, R.drawable.pic4, R.drawable.pic5,
- R.drawable.pic6, R.drawable.pic7, R.drawable.pic8,
- };
- MyAdapter(Context context){
- this.context = context;
- }
- public int getCount() {
- return imgs.length;
- }
- public Object getItem(int item) {
- return item;
- }
- public long getItemId(int id) {
- return id;
- }
- //創建View方法
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView imageView;
- if (convertView == null) {
- imageView = new ImageView(context);
- imageView.setLayoutParams(new GridView.LayoutParams(75, 75));//設置ImageView對象布局
- imageView.setAdjustViewBounds(false);//設置邊界對齊
- imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);//設置刻度的類型
- imageView.setPadding(8, 8, 8, 8);//設置間距
- }
- else {
- imageView = (ImageView) convertView;
- }
- imageView.setImageResource(imgs[position]);//為ImageView設置圖片資源
- return imageView;
- }
- }
main.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"
- >
- <GridView
- android:id="@+id/GridView1"
- android:layout_width_="wrap_content"
- android:layout_height="wrap_content"
- android:columnWidth="90dp"
- android:numColumns="3"
- android:verticalSpacing="10dp"
- android:horizontalSpacing="10dp"
- android:stretchMode="columnWidth"
- android:gravity="center"
- />
- </LinearLayout>
效果圖:
第二個例子:
MainActivity.java
- package com.android.gridview2.activity;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.GridView;
- import android.widget.SimpleAdapter;
- public class MainActivity extends Activity {
- private GridView gv;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.gridview);
- //準備要添加的數據條目
- List<Map<String, Object>> items = new ArrayList<Map<String,Object>>();
- for (int i = 0; i < 9; i++) {
- Map<String, Object> item = new HashMap<String, Object>();
- item.put("imageItem", R.drawable.icon);//添加圖像資源的ID
- item.put("textItem", "icon" + i);//按序號添加ItemText
- items.add(item);
- }
- //實例化一個適配器
- SimpleAdapter adapter = new SimpleAdapter(this,
- items,
- R.layout.grid_item,
- new String[]{"imageItem", "textItem"},
- new int[]{R.id.image_item, R.id.text_item});
- //獲得GridView實例
- gv = (GridView)findViewById(R.id.mygridview);
- //為GridView設置適配器
- gv.setAdapter(adapter);
- }
- }
gridview.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width_="wrap_content"
- android:layout_height="wrap_content"
- >
- <GridView
- android:id="@+id/mygridview"
- android:numColumns="3"
- android:gravity="center_horizontal"
- android:layout_width_="wrap_content"
- android:layout_height="wrap_content"
- android:stretchMode="columnWidth"
- />
- </LinearLayout>
grid_item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width_="wrap_content"
- android:layout_height="fill_parent"
- android:paddingBottom="6dip"
- >
- <ImageView
- android:id="@+id/image_item"
- android:layout_width_="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- />
- <TextView
- android:id="@+id/text_item"
- android:layout_below="@+id/image_item"
- android:layout_height="wrap_content"
- android:layout_width_="wrap_content"
- android:layout_centerHorizontal="true"
- />
- </RelativeLayout>
效果圖:
第三個例子:
MainActivity.java
- package com.android.gridview3;
- import java.util.ArrayList;
- import java.util.List;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.AdapterView;
- import android.widget.BaseAdapter;
- import android.widget.GridView;
- import android.widget.ImageView;
- import android.widget.TextView;
- import android.widget.Toast;
- import android.widget.AdapterView.OnItemClickListener;
- public class MainActivity extends Activity
- {
- private GridView gridView;
- //圖片的文字標題
- private String[] titles = new String[]
- { "pic1", "pic2", "pic3", "pic4", "pic5", "pic6", "pic7", "pic8", "pic9"};
- //圖片ID數組
- private int[] images = new int[]{
- R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
- R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
- R.drawable.pic7, R.drawable.pic8,R.drawable.pic9
- };
- @Override
- public void onCreate(Bundle savedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- gridView = (GridView) findViewById(R.id.gridview);
- PictureAdapter adapter = new PictureAdapter(titles, images, this);
- gridView.setAdapter(adapter);
- gridView.setOnItemClickListener(new OnItemClickListener()
- {
- public void onItemClick(AdapterView<?> parent, View v, int position, long id)
- {
- Toast.makeText(MainActivity.this, "pic" + (position+1), Toast.LENGTH_SHORT).show();
- }
- });
- }
- }
- //自定義適配器
- class PictureAdapter extends BaseAdapter{
- private LayoutInflater inflater;
- private List<Picture> pictures;
- public PictureAdapter(String[] titles, int[] images, Context context)
- {
- super();
- pictures = new ArrayList<Picture>();
- inflater = LayoutInflater.from(context);
- for (int i = 0; i < images.length; i++)
- {
- Picture picture = new Picture(titles[i], images[i]);
- pictures.add(picture);
- }
- }
- @Override
- public int getCount()
- {
- if (null != pictures)
- {
- return pictures.size();
- } else
- {
- return 0;
- }
- }
- @Override
- public Object getItem(int position)
- {
- return pictures.get(position);
- }
- @Override
- public long getItemId(int position)
- {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent)
- {
- ViewHolder viewHolder;
- if (convertView == null)
- {
- convertView = inflater.inflate(R.layout.picture_item, null);
- viewHolder = new ViewHolder();
- viewHolder.title = (TextView) convertView.findViewById(R.id.title);
- viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
- convertView.setTag(viewHolder);
- } else
- {
- viewHolder = (ViewHolder) convertView.getTag();
- }
- viewHolder.title.setText(pictures.get(position).getTitle());
- viewHolder.image.setImageResource(pictures.get(position).getImageId());
- return convertView;
- }
- }
- class ViewHolder
- {
- public TextView title;
- public ImageView image;
- }
- class Picture
- {
- private String title;
- private int imageId;
- public Picture()
- {
- super();
- }
- public Picture(String title, int imageId)
- {
- super();
- this.title = title;
- this.imageId = imageId;
- }
- public String getTitle()
- {
- return title;
- }
- public void setTitle(String title)
- {
- this.title = title;
- }
- public int getImageId()
- {
- return imageId;
- }
- public void setImageId(int imageId)
- {
- this.imageId = imageId;
- }
- }
main.xml
- <?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"
- />
picture_item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/root"
- android:orientation="vertical"
- android:layout_width_="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="5dp"
- >
- <ImageView
- android:id="@+id/image"
- android:layout_width_="100dp"
- android:layout_height="150dp"
- android:layout_gravity="center"
- android:scaleType="fitXY"
- android:padding="4dp"
- />
- <TextView
- android:id="@+id/title"
- android:layout_width_="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:gravity="center_horizontal"
- />
- </LinearLayout>
效果圖:
本文出自 「IT的點點滴滴」 博客,請務必保留此出處http://liangruijun.blog.51cto.com/3061169/647355
推薦閱讀: