注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

无线时代辐射无穷

抓紧生宝宝,小心辐射

 
 
 

日志

 
 

Android中使用Gridview展示图片列表  

2011-09-24 12:05:24|  分类: android |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

gridview是一项显示二维的viewgroup,可滚动的网格。网格项时自动插入的布局使用listadapter。
1.创建一个新的项目:gridview.

2,打开 res/layout/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/gridview" 
  9.          android:layout_width="fill_parent" 
  10.          android:layout_height="fill_parent" 
  11.          android:columnWidth="90dp" 
  12.          android:numColumns="auto_fit" 
  13.          android:verticalSpacing="10dp" 
  14.          android:horizontalSpacing="10dp" 
  15.          android:stretchMode="columnWidth" 
  16.          android:gravity="center" 
  17.          />   
  18. </LinearLayout> 

做好以后就可以在屏幕上显示一个grid view

3.打开gridview.java首先要导入包:

  1. package cn.gridview;  
  2. import android.widget.GridView;  
  3. import android.widget.Toast;  
  4. import android.app.Activity;  
  5. import android.os.Bundle;  
  6. import android.widget.AdapterView.OnItemClickListener;  
  7. import android.widget.AdapterView;  
  8. import android.view.View;  
  9. 在onCreate添加方法:  
  10.  public void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         setContentView(R.layout.main);  
  13.         GridView gridview=(GridView)findViewById(R.id.gridview);//找到main.xml中定义gridview 的id  
  14.         gridview.setAdapter(new ImageAdapter(this));//调用ImageAdapter.java  
  15.         gridview.setOnItemClickListener(new OnItemClickListener(){//监听事件  
  16.          public void onItemClick(AdapterView<?> parent, View view, int position, long id)   
  17.          {  
  18.           Toast.makeText(gridview.this, ""+position,Toast.LENGTH_SHORT).show();//显示信息;  
  19.          }  
  20.         });  
  21.     }  
  22. ImageAdapter.java  
  23. package cn.gridview;  
  24. import android.view.View;  
  25. import android.view.ViewGroup;  
  26. import android.widget.BaseAdapter;  
  27. import android.content.Context;  
  28. import android.widget.ImageView;  
  29. import android.widget.GridView;  
  30. public class ImageAdapter extends BaseAdapter {  
  31.  private Context mContext;  
  32.    
  33.  public ImageAdapter(Context c)  
  34.  {  
  35.   mContext=c;  
  36.  }  
  37.  @Override  
  38.  public int getCount() {  
  39.   // TODO Auto-generated method stub  
  40.   return mThumbIds.length;  
  41.  }  
  42. @Override  
  43.  public Object getItem(int position) {  
  44.   // TODO Auto-generated method stub  
  45.   return null;  
  46.  }  
  47. @Override  
  48.  public long getItemId(int position) {  
  49.   // TODO Auto-generated method stub  
  50.   return 0;  
  51.  }  
  52.  @Override  
  53.  public View getView(int position, View convertView, ViewGroup parent) {  
  54.   // TODO Auto-generated method stub  
  55.     
  56.   ImageView imageview;  
  57.   if(convertView==null)  
  58.   {  
  59.    imageview=new ImageView(mContext);  
  60.    imageview.setLayoutParams(new GridView.LayoutParams(85, 85));  
  61.    imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);  
  62.    imageview.setPadding(8,8,8,8);  
  63.  }  
  64.   else  
  65.   {  
  66.    imageview=(ImageView) convertView;  
  67.   }  
  68.   imageview.setImageResource(mThumbIds[position]);  
  69.   return imageview;  
  70.   }  
  71. private Integer[] mThumbIds={//显示的图片数组   
  72.   R.drawable.sample_2,R.drawable.sample_3,  
  73.   R.drawable.sample_4,R.drawable.sample_5,  
  74.   R.drawable.sample_6,R.drawable.sample_7,  
  75.   R.drawable.sample_0,R.drawable.sample_1,  
  76.   R.drawable.sample_2,R.drawable.sample_3,  
  77.   R.drawable.sample_4,R.drawable.sample_5,  
  78.   R.drawable.sample_6,R.drawable.sample_7,  
  79.   R.drawable.sample_0,R.drawable.sample_1,  
  80.   R.drawable.sample_2,R.drawable.sample_3,  
  81.   R.drawable.sample_4,R.drawable.sample_5,  
  82.   R.drawable.sample_6,R.drawable.sample_7,  
  83.  };  

运行后界面如下:

Android中使用Gridview展示图片列表 - wolfgangkiefer - 嘎嘎阅读器

 附加:
在android中进行图片操作,特别是使用BitmapFactory.decodeByteArray处理byte[]类型到Bitmap中时,容易产生内存溢出或不足的问题,主要原因是decodeByteArray采用的Native方式,需要自己即时清理内存,过关。

 

GridView图片文字结合:
package com.wljie.adpater;  
  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
  
import Android.app.Activity;  
import Android.content.ContentResolver;  
import Android.database.Cursor;  
import Android.os.Bundle;  
import Android.provider.MediaStore.Images.Thumbnails;  
import Android.util.Log;  
import Android.widget.GridView;  
  
public class Main extends Activity {  
    /** Called when the activity is first created. */  
     private ContentResolver cr;  
     private final String TAG="Main";  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        GridView gridView = (GridView) findViewById(R.id.gridview);  
        List<HashMap<String, String>> list = getimageList();  
        gridView.setAdapter(new MyAdpater(this, list));  
    }  
  
  
     private   List<HashMap<String, String>>  getimageList() {  
            List<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();  
            cr = getContentResolver();    
            String[] projection = { Thumbnails._ID, Thumbnails.IMAGE_ID,  Thumbnails.DATA };    
            Cursor cur = cr.query(Thumbnails.EXTERNAL_CONTENT_URI, projection,null, null, null);   
            if (cur.moveToFirst()) {    
                int _id;    
                int image_id;    
                String image_path;    
                int _idColumn = cur.getColumnIndex(Thumbnails._ID);    
                int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID);    
                int dataColumn = cur.getColumnIndex(Thumbnails.DATA);    
                do {    
                    _id = cur.getInt(_idColumn);    
                    image_id = cur.getInt(image_idColumn);    
                    image_path = cur.getString(dataColumn);    
                    Log.i(TAG, _id + " image_id:" + image_id + " path:"+ image_path + "---");    
                    HashMap hash = new HashMap();    
                    hash.put("image_id", image_id +"");    
                    hash.put("path", image_path);    
                    list.add(hash);    
        
                } while (cur.moveToNext());    
        
            }  
            return list;    
     }  

package com.wljie.adpater;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import <a href="http://www.linuxidc.com/topicnews.aspx?tid=11" title="Android">Android</a>.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.widget.GridView;

public class Main extends Activity {
    /** Called when the activity is first created. */
  private ContentResolver cr;
  private final String TAG="Main";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GridView gridView = (GridView) findViewById(R.id.gridview);
        List<HashMap<String, String>> list = getimageList();
        gridView.setAdapter(new MyAdpater(this, list));
    }


  private   List<HashMap<String, String>>  getimageList() {
    List<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
      cr = getContentResolver(); 
         String[] projection = { Thumbnails._ID, Thumbnails.IMAGE_ID,  Thumbnails.DATA }; 
         Cursor cur = cr.query(Thumbnails.EXTERNAL_CONTENT_URI, projection,null, null, null);
         if (cur.moveToFirst()) { 
             int _id; 
             int image_id; 
             String image_path; 
             int _idColumn = cur.getColumnIndex(Thumbnails._ID); 
             int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID); 
             int dataColumn = cur.getColumnIndex(Thumbnails.DATA); 
             do { 
                 _id = cur.getInt(_idColumn); 
                 image_id = cur.getInt(image_idColumn); 
                 image_path = cur.getString(dataColumn); 
                 Log.i(TAG, _id + " image_id:" + image_id + " path:"+ image_path + "---"); 
                 HashMap hash = new HashMap(); 
                 hash.put("image_id", image_id +""); 
                 hash.put("path", image_path); 
                 list.add(hash); 
  
             } while (cur.moveToNext()); 
  
         }
   return list; 
  }
}
view plaincopy to clipboardprint?
package com.wljie.adpater;  
  
import java.util.HashMap;  
import java.util.List;  
  
  
import Android.content.Context;  
import Android.graphics.Bitmap;  
import Android.graphics.BitmapFactory;  
import Android.view.LayoutInflater;  
import Android.view.View;  
import Android.view.ViewGroup;  
import Android.widget.BaseAdapter;  
import Android.widget.ImageView;  
import Android.widget.TextView;  
  
public class MyAdpater extends BaseAdapter {  
  
    private List<HashMap<String, String>> list ;  
    private Context context;  
      
    public MyAdpater(Context context,List<HashMap<String, String>> list) {  
        this.list = list;  
        this.context = context;  
    }  
      
    @Override  
    public int getCount() {  
        return list.size();  
    }  
  
    @Override  
    public Object getItem(int position) {  
        return list.get(position);  
    }  
  
    @Override  
    public long getItemId(int position) {  
        return position;  
    }  
  
    @Override  
    public View getView(int position, View convertView, ViewGroup parent) {  
        MyView tag;  
        if (convertView == null) {  
            View v = LayoutInflater.from(context).inflate(R.layout.night_item, null);  
            tag  = new MyView();  
            tag.imageView = (ImageView) v.findViewById(R.id.itemImage);  
//          tag.textView = (TextView) v.findViewById(R.id.itemText);   
//          tag.textView2 = (TextView) v.findViewById(R.id.desc);   
            v.setTag(tag);  
            convertView = v;  
        }else{  
            tag= (MyView)convertView.getTag();  
        }  
        String image_path = list.get(position).get("path");  
        String text = list.get(position).get("image_id");  
        Bitmap bitmap = BitmapFactory.decodeFile(image_path);  
        Bitmap newBit = Bitmap.createScaledBitmap(bitmap, 100, 80, true);   
        tag.imageView.setImageBitmap(newBit);  
//      tag.textView.setText(text);   
//      tag.textView2.setText(text);   
        return convertView;  
    }  
  
    class MyView{  
        ImageView imageView;  
        TextView textView;  
        TextView textView2;  
    }  

下面是xml的配制:

<?xml version="1.0" encoding="utf-8"?>  
 <!--  
  Android:numColumns="auto_fit" ,GridView的列数设置为自动  
  Android:columnWidth="90dp",每列的宽度,也就是Item的宽度  
  Android:stretchMode="columnWidth",缩放与列宽大小同步  
  Android:verticalSpacing="10dp",两行之间的边距,如:行一(NO.0~NO.2)与行二(NO.3~NO.5)间距为10dp  
  Android:horizontalSpacing="10dp",两列之间的边距  
 -->  
<GridView xmlns:Android="http://schemas.android.com/apk/res/android"  
 Android:id="@+id/gridview"   
 Android:layout_width="fill_parent"  
 Android:layout_height="wrap_content"  
 Android:numColumns="2"  
 Android:verticalSpacing="10dp"  
 Android:horizontalSpacing="4dp"  
 Android:stretchMode="columnWidth"  
 Android:gravity="center" /> 
item.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="vertical"  
  Android:padding="6dp"  
>  
<LinearLayout  
 Android:layout_height="wrap_content"  
 Android:orientation="horizontal"  
 Android:paddingBottom="2dp"  
  
 Android:layout_width="wrap_content">  
     <ImageView Android:layout_height="wrap_content"  
      Android:layout_width="fill_parent" android:layout_centerHorizontal="true"  
      Android:id="@+id/itemImage">  
     </ImageView>  
  
</LinearLayout>  
  
  </LinearLayout> 

 

  评论这张
 
阅读(2674)| 评论(1)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017