欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android开发学习笔记 Gallery和GridView浅析

程序员文章站 2022-04-12 12:25:15
一.gallery的简介 gallery(画廊)是一个锁定中心条目并且拥有水平滚动列表的视图,一般用来浏览图片,并且可以响应事件显示信息。gallery还可以和image...

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

package com.android.gallerydemo; 
 
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.gallery; 
import android.widget.imageview; 
import android.widget.toast; 
 
public class mainactivity extends activity { 
 
  private gallery gallery; 
  @override 
  public void oncreate(bundle savedinstancestate) { 
 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.main); 
    gallery = (gallery)findviewbyid(r.id.gallery); 
    //设置图片适配器 
    gallery.setadapter(new imageadapter(this)); 
    //设置监听器 
    gallery.setonitemclicklistener(new onitemclicklistener() { 
     @override 
     public void onitemclick(adapterview<?>parent, view v, int position, long id) { 
      toast.maketext(mainactivity.this, "点击了第"+(position+1)+"张图片", toast.length_long).show(); 
     } 
   }); 
  } 
} 
 
class imageadapter extends baseadapter{ 
 //声明context  
 private context context; 
 //图片源数组 
 private integer[] imageinteger={ 
     r.drawable.pic1, 
     r.drawable.pic2, 
     r.drawable.pic3, 
     r.drawable.pic4, 
     r.drawable.pic5, 
     r.drawable.pic6, 
     r.drawable.pic7 
 }; 
  
 //声明 imageadapter 
 public imageadapter(context c){ 
   context = c; 
 } 
 
 @override 
 //获取图片的个数 
 public int getcount() { 
   return imageinteger.length; 
 } 
 
 @override 
 //获取图片在库中的位置 
 public object getitem(int position) { 
 
   return position; 
 } 
 
 @override 
 //获取图片在库中的位置 
 public long getitemid(int position) { 
   // todo auto-generated method stub 
   return position; 
 } 
 
 @override 
 public view getview(int position, view convertview, viewgroup parent) { 
 
   imageview imageview = new imageview(context); 
   //给imageview设置资源 
   imageview.setimageresource(imageinteger[position]); 
   //设置比例类型 
   imageview.setscaletype(imageview.scaletype.fit_xy); 
   //设置布局 图片128x192显示 
   imageview.setlayoutparams(new gallery.layoutparams(128, 192)); 
   return imageview; 
 } 
}

main.xml

<?xml version="1.0" encoding="utf-8"?> 
<gallery xmlns: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" 
/>

效果图:

Android开发学习笔记 Gallery和GridView浅析

gallery和imageswitcher组件结合使用的例子:
mainactivity.java

package com.android.gallerytest; 
 
import android.app.activity; 
import android.content.context; 
import android.os.bundle; 
import android.view.view; 
import android.view.viewgroup; 
import android.view.window; 
import android.view.animation.animationutils; 
import android.widget.adapterview; 
import android.widget.baseadapter; 
import android.widget.gallery; 
import android.widget.imageswitcher; 
import android.widget.imageview; 
import android.widget.adapterview.onitemselectedlistener; 
import android.widget.gallery.layoutparams; 
import android.widget.viewswitcher.viewfactory; 
 
public class mainactivity extends activity implements onitemselectedlistener, 
    viewfactory { 
   
  private imageswitcher mswitcher; 
  //大图片对应的缩略图源数组 
  private integer[] 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 }; 
  //大图片源数组 
  private integer[] 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 
  public void oncreate(bundle savedinstancestate) { 
    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)); 
 
    gallery g = (gallery) findviewbyid(r.id.gallery); 
     
    //添加onitemselectedlistener监听器 
    g.setadapter(new imageadapter(this)); 
    g.setonitemselectedlistener(this); 
 
  } 
  //创建内部类imageadapter 
  public class imageadapter extends baseadapter { 
    public imageadapter(context c) { 
      mcontext = c; 
    } 
    public int getcount() { 
      return mthumbids.length; 
    } 
    public object getitem(int position) { 
      return position; 
    } 
    public long getitemid(int position) { 
      return position; 
    } 
    public view getview(int position, view convertview, viewgroup parent) { 
      imageview i = new imageview(mcontext); 
 
      i.setimageresource(mthumbids[position]); 
      //设置边界对齐 
      i.setadjustviewbounds(true); 
      //设置布局参数 
      i.setlayoutparams(new gallery.layoutparams( 
          layoutparams.wrap_content, layoutparams.wrap_content)); 
      //设置背景资源 
      i.setbackgroundresource(r.drawable.picture_frame); 
      return i; 
    } 
    private context mcontext; 
  } 
 
  @override 
  //实现onitemselected()方法,更换图片 
  public void onitemselected(adapterview<?> adapter, view v, int position, 
      long id) { 
    //设置图片资源 
    mswitcher.setimageresource(mimageids[position]); 
  } 
 
  @override 
  public void onnothingselected(adapterview<?> arg0) { 
 
  } 
 
  @override 
  //实现makeview()方法,为imageview设置布局格式 
  public view makeview() { 
    imageview i = new imageview(this); 
    //设置背景颜色 
    i.setbackgroundcolor(0xff000000); 
    //设置比例类型 
    i.setscaletype(imageview.scaletype.fit_center); 
    //设置布局参数 
    i.setlayoutparams(new imageswitcher.layoutparams( 
        layoutparams.fill_parent, layoutparams.fill_parent)); 
    return i; 
  } 
}

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" 
  >   
  <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>

效果图:

Android开发学习笔记 Gallery和GridView浅析

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

效果图:

Android开发学习笔记 Gallery和GridView浅析

第二个例子:
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> 

效果图:

Android开发学习笔记 Gallery和GridView浅析

第三个例子:
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> 

效果图:

Android开发学习笔记 Gallery和GridView浅析

本文出自 “it的点点滴滴” 博客