Android - 如何创建图像选择器

时间:2012-01-26 13:49:17

标签: android image selector

在我的应用程序中,我需要使用一些让用户从设备中选择图像的东西 如何做到这一点很简单?

记住我会在选中后使用该图片。

提前致谢。

2 个答案:

答案 0 :(得分:2)

您可以尝试以下操作,打开图库并让用户选择图像。

Intent i = new Intent(Intent.ACTION_PICK,  
     android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE);

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

switch(requestCode) { 
case REQ_CODE_PICK_IMAGE:
    if(resultCode == RESULT_OK){  
        Uri selectedImage = imageReturnedIntent.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();


        Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
    }
}

}

'selectedImage'是选定的图像,因此您现在可以在应用程序的其余部分中使用它。

答案 1 :(得分:1)

使用代码从图库中选择图像

galleryPic.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            Util.DogDye = false;
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);

            startActivityForResult(
                    Intent.createChooser(intent, "Complete action using"),
                    1);

        }
    });

之后添加一个新方法

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if (resultCode != RESULT_OK) return;

    switch (requestCode) {

    case 1:
        if (data != null) {
            selectedImageUri = data.getData();
            String selectedImagePath = getPath(path);
BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
Bitmap btemp = BitmapFactory.decodeFile(selectedImagePath,
                        options);
          /// use btemp Image file 

        }
        break;
    }

}


   public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}