在GridView中显示SD卡上的全部图片

来源:互联网 发布:阿里云手机验证码 编辑:程序博客网 时间:2024/04/28 02:58

1、布局文件

<?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" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="SD卡上的全部图片" /><GridView android:id="@+id/gridView1" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_marginTop="10px"android:horizontalSpacing="3px"android:verticalSpacing="3px"android:numColumns="4"/>    </LinearLayout>

2、MainActivity中定义一个用于保存图片路径的List集合对象

private List<String> imagePath = new ArrayList<String>();//图片文件的路径

3、定义一个保存合法的图片文件格式的字符串数组

private static String[] imageFormatSet = new String[]{"jpg","png","gif"};//合法的图片文件格式//判断是否为图片文件private static boolean isImageFile(String path){for (String format : imageFormatSet) {//遍历数组if(path.contains(format)){//判断是否为合法的图片文件return true;}}return false;}

4、编写getFiles()方法,用于遍历指定路径

private void getFiles(String url){File files = new File(url);//创建文件对象File[] file = files.listFiles();try {for (File f : file) {//通过for循环遍历获取到的文件数组if(f.isDirectory()){//如果是目录,也就是文件夹getFiles(f.getAbsolutePath());//递归调用}else{if(isImageFile(f.getPath())){//如果是图片路径imagePath.add(f.getPath());//将文件的路径添加到List集合中}}}} catch (Exception e) {e.printStackTrace();}}

5、在onCreate方法中,获得SD卡的路径,并调用getFile()方法获取SD卡上的全部图片,当SD卡上不存在图片文件是返回

String sdpath = Environment.getExternalStorageDirectory()+"/";//获取SD卡的路径        getFiles(sdpath);//调用getFiles()方法获取SD卡上的全部图片        if(imagePath.size()<1){//如果不存在图片文件        return;        }


6、获取GridView组件,然后创建BaseAdapter类的对象,并重写其中的getView()、geItemId()、getItem()和getCount()方法

GridView gridView = (GridView)findViewById(R.id.gridView1);//获取GridView组件        BaseAdapter adapter = new BaseAdapter() {@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ImageView imageView;//声明ImageView的对象if(convertView==null){imageView = new ImageView(MainActivity.this);//实例化ImageView的对象//设置推向的宽度和高度imageView.setAdjustViewBounds(true);imageView.setMaxWidth(150);imageView.setMaxHeight(113);imageView.setPadding(5, 5, 5, 5);//设置ImageView的内边距}else{imageView = (ImageView)convertView;}//为ImageView设置要显示的图片Bitmap bm = BitmapFactory.decodeFile(imagePath.get(position));imageView.setImageBitmap(bm);return imageView;}//获取当前选项的id@Overridepublic long getItemId(int position) {return position;}//获取当前选项@Overridepublic Object getItem(int position) {return position;}//获得数量@Overridepublic int getCount() {return imagePath.size();}};gridView.setAdapter(adapter);//将适配器与GridView关联

 无图无真相

0 0
原创粉丝点击