1. 程式人生 > >Android實現獲取手機裡面的所有圖片

Android實現獲取手機裡面的所有圖片

public class MainActivity extends Activity {
//檢視圖片按鈕
    private Button look;
    private Button add;
//顯示圖片名稱的list
    ListView show_list;
    ArrayList names = null;
    ArrayList descs= null;
    ArrayList fileNames = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        look = (Button) findViewById(R.id.look);
        add = (Button) findViewById(R.id.add);
        show_list = (ListView) findViewById(R.id.show_list);
        look.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                names = new ArrayList();
                descs = new ArrayList();
                fileNames = new ArrayList();
                Cursor cursor = getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
                while (cursor.moveToNext()) {
                    //獲取圖片的名稱
                    String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
                    //獲取圖片的生成日期
                    byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    //獲取圖片的詳細資訊
                    String desc = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DESCRIPTION));
                    names.add(name);
                    descs.add(desc);
                    fileNames.add(new String(data, 0, data.length - 1));
                }
                List<Map<String, Object>> listItems = new ArrayList<>();
                for (int i = 0; i < names.size(); i++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", names.get(i));
                    map.put("desc", descs.get(i));
                    listItems.add(map);
                }
                //設定adapter
                SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, listItems,
                        R.layout.line, new String[]{"name", "desc"}, new int[]{R.id.name, R.id.desc});

                show_list.setAdapter(adapter);
            }
        });

        ///list的點選事件
    show_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            View viewDiag = getLayoutInflater().inflate(R.layout.view,null);
            ImageView image = (ImageView)viewDiag.findViewById(R.id.image);
            image.setImageBitmap(BitmapFactory.decodeFile((String) fileNames.get(i)));
            new AlertDialog.Builder(MainActivity.this).setView(viewDiag)
                    .setPositiveButton("確定",null).show();
        }
    });
    }
}
<!--獲取手機儲存卡許可權-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>