来自SD卡的照片显示为位图ID代码

时间:2015-03-19 08:48:02

标签: android bitmap android-arrayadapter android-gridview android-sdcard

我的代码似乎做了两件事:从SD卡目录中提取照片,并从可绘制资源添加“占位符”照片以填充GridView。但是,我只看到两个操作看起来似乎是Bitmap对象哈希码(如果这是正确的术语)。知道如何让图像显示出来吗?

enter image description here

PhotoTab.java

package org.azurespot.cutecollection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import org.azurespot.R;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by mizu on 2/8/15.
 */
public class PhotoTab extends Fragment{

    private GridView gridView;
    File[] files;
    ArrayList<Bitmap> photoList = new ArrayList<>();
    ArrayAdapter<Bitmap> adapter;

    public PhotoTab(){
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.photo_tab, container, false);

        adapter = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_list_item_1, photoList);

        // with fragments, make sure you include the rootView when finding id
        gridView = (GridView) v.findViewById(R.id.photo_grid);

        // Set the Adapter to GridView
        gridView.setAdapter(adapter);

        // read contents of SD card
        loadSDCard();

        // add the default icons remaining, to GridView, if less than 24 files on SD card
        for (int i = 0; i < (24 - photoList.size()); i++) {

            adapter.add(BitmapFactory.decodeResource(getResources(), R.drawable.ic_photo_placeholder));
            adapter.notifyDataSetChanged();
            i++;
        }

        return v;
    }

    private void loadSDCard(){

        try {
            // gets directory CutePhotos from sd card
            File baseDir = Environment.getExternalStorageDirectory();
            File cutePhotoDir = new File(baseDir, "/Documents/CutePhotos");
            // lists all files in CutePhotos, loads in Files[] array
            files = cutePhotoDir.listFiles();


            for (File singleFile : files) {
                String filePath = singleFile.getAbsolutePath();
                Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                photoList.add(bitmap);

            }

            adapter.addAll(photoList);
            adapter.notifyDataSetChanged();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您用作行android.R.layout.simple_list_item_1的布局,包含TextViewArrayAdapter只是调用toString(),数据集的项目分配返回此TextView的值。要解决此问题,您必须继承ArrayAdapterBaseAdapter并覆盖getView,以自定义GridView项的方面