找出手机全部图片放到GridView里

效果图示例android

 

//把手机里sdcard的全部图片找出来 像第一张图那样缓存

//而后点击其中任意一张图片时 就查看原图ide

 

=====================================================工具

 

一、添加读和写的权限布局

二、activity_main.xml布局文件this

 

代码url

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >code

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000"
        android:numColumns="auto_fit" />orm

    <TextView
        android:id="@+id/empty_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/gridview"
        android:text="没有图片数据" />xml

</RelativeLayout>

 

-----------------------------------------------

 

 

 

三、写一个工具类用于对sdcard的读写 的操做

代码

 

//操做SDCARD的文件工具类
public class FileUtil {
//存放图片的路径
 private static final String CACHE_DIR = Environment.getExternalStorageDirectory() + "/my_caches/images";

 private static int COMP_JPG = 0;
 private static int COMP_PNG = 1;
//判断sdcard 是否挂载(是否有sdcard)
 public static boolean isMounted(){
  //获取手机设备的sdcard状态
  String state = Environment.getExternalStorageState();
  //MOUNTED -- 安装
  return state.equals(Environment.MEDIA_MOUNTED);
 }

 //获取sdcard文件 根路径的绝对路径
 public static String getSDCARD(){
  return Environment.getExternalStorageDirectory().getAbsolutePath();
 }

 //获取文件名
 public static String getFilename(String url){
  return url.substring(url.lastIndexOf('/') + 1);
 }

 //保存文件 方法1
 public static void sava1(String url,byte[] data){
  //判断是否有sdcard
  if(!isMounted()){
  return ; 
  }
  //有sdcard
  //判断是否有缓存文件夹
  File dir = new File(CACHE_DIR);
  if(!dir.exists()){
   //不存在缓存文件夹 建立文件夹用来保存文件
   dir.mkdirs();
  }
  //把文件 数据存到sdcard
  File file = new File(dir,getFilename(url));
  try {
   FileOutputStream fos = new FileOutputStream(file);
   fos.write(data);
   
   fos.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 //保存文件 方法2
 public static void sava2(String url,Bitmap bitmap,int format){
  //判断 是否有sdcard
  if(!isMounted()){
   return ;
  }
  File dir = new File(CACHE_DIR);
  if(!dir.exists()){
   dir.mkdirs();
  }
  //把 文件数据 写到 sdcard
  File file = new File(dir,getFilename(url));
  try {
   FileOutputStream fos = new FileOutputStream(file);
   //把图片文件写入缓存
   bitmap.compress((format == COMP_JPG?CompressFormat.JPEG:CompressFormat.PNG), 100, fos);
  
   fos.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }
 //读取图片
 public static Bitmap readImage(String url){
  if(!isMounted()){
   return null;
  }
  File file = new File(CACHE_DIR,getFilename(url));
  if(file.exists()){
   return BitmapFactory.decodeFile(file.getAbsolutePath());
  }
  return null;
 }
 
 //清空 缓存目录
 public void clearCaches(){
  File dir = new File(CACHE_DIR);
  File[] file_datas = dir.listFiles();
  for(File file : file_datas){
   file.delete();
  }
 }
 
 //生成略缩图
 public static Bitmap creatThumbnail(String filepath,int newWidth,int newHeight){
  BitmapFactory.Options options = new BitmapFactory.Options();
  //
  options.inJustDecodeBounds = true;
  //目的:不生成bitmap数据,可是要获取原图的参数值
  BitmapFactory.decodeFile(filepath, options);
  //原有宽高
  int originalWidth = options.outWidth;
  int originalHeight = options.outHeight;
  //按比例缩小的宽高
  int width = originalWidth/newWidth;
  int height = originalHeight/newHeight;
  
  options.inSampleSize = height > width? height : width;
  
  options.inJustDecodeBounds = false;
  
  return BitmapFactory.decodeFile(filepath, options);
 }
 
}

 

---------------------------------------------------------------

 

MainActivity 类

 

代码

 

public class MainActivity extends Activity {

 private MyAdapter adapter;
 private GridView gridview;
 private TextView empty_textview;
 private List<String> img_path = new ArrayList<String>();
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  this.gridview = (GridView) this.findViewById(R.id.gridview);
  this.empty_textview = (TextView) this.findViewById(R.id.empty_textview);
  //setEmptyView方法 -- gridview没有数据 就会启动该方法
  gridview.setEmptyView(empty_textview);
  
  //获取sdcard根目录
  String sd_path = FileUtil.getSDCARD();
  //使用递归 遍历 sdcard 把找到的图片 设置到gridview
  find_images(sd_path);
  
  adapter = new MyAdapter(img_path);
  gridview.setAdapter(adapter);
 }
 //查找图片的 递归 方法
 private void find_images(String sd_path) {
  File file = new File(sd_path);
  //用file.listFiles()获取file目录下的全部文件夹和文件
  File[] files = file.listFiles();
  if(files != null && files.length > 0){
   for(File f :files){
    if(f.isDirectory()){//若是是文件夹继续查找
     find_images(f.getAbsolutePath());
    }else{
     //若是是文件 在判断是不是 图片
     if(f.getPath().endsWith("jpg") || f.getPath().endsWith("png")){
      //把图片路径 保存在一个集合里
     // Log.i("data", "img_path:" + img_path.toString());
      img_path.add(f.getPath());
     }
    }
   }
  }
 }
 //适配器类
 class MyAdapter extends BaseAdapter{

  private List<String> list;  public MyAdapter(List<String> img_path) {   this.list = img_path;  }  @Override  public int getCount() {   return this.list.size();  }  @Override  public Object getItem(int position) {   return this.list.get(position);  }  @Override  public long getItemId(int position) {   return position;  }  @Override  public View getView(final int position, View convertView, ViewGroup parent) {   ImageView imageview = null;   if(convertView == null){    imageview = new ImageView(parent.getContext());    imageview.setMaxHeight(150);    imageview.setMaxWidth(90);    imageview.setBackgroundResource(R.drawable.image_border);    imageview.setPadding(5, 5, 5, 5);   }else{    imageview = (ImageView) convertView;   }   //设置数据  -- 调用工具类的略缩图方法 -- 把点中的图片修改  Bitmap bitmap = FileUtil.creatThumbnail(this.list.get(position), 150, 90);  imageview.setImageBitmap(bitmap);  //每张图片 的点击 事件  //点中后 查看原图  imageview.setOnClickListener(new OnClickListener() {      @Override   public void onClick(View v) {    Intent intent = new Intent();    intent.setAction(intent.ACTION_VIEW);    intent.setDataAndType(Uri.fromFile(new File(list.get(position))), "image/*");    startActivity(intent);   }  });  return imageview;  }   }}

相关文章
相关标签/搜索