如何打开图库来选择多个图像?

时间:2016-08-30 11:10:04

标签: android android-intent android-gallery

我想打开具有多种图像选择功能的图库,我正在使用以下代码。

$weekNumber = date("W"); 

它会打开图库应用,但不允许我选择多个图像。

5 个答案:

答案 0 :(得分:1)

单击并按住以选择多个图像。不要点击图片。您也可以使用此接收这些图像。

int PICK_IMAGE_MULTIPLE = 1;
String imageEncoded;
List<String> imagesEncodedList;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        // When an Image is picked
        if (requestCode == 1 && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            imagesEncodedList = new ArrayList<String>();
            if(data.getData()!=null){

                Uri mImageUri=data.getData();

                // Get the cursor
                Cursor cursor = getContentResolver().query(mImageUri,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

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

            }else {
                if (data.getClipData() != null) {
                    ClipData mClipData = data.getClipData();
                    ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                    for (int i = 0; i < mClipData.getItemCount(); i++) {

                        ClipData.Item item = mClipData.getItemAt(i);
                        Uri uri = item.getUri();
                        mArrayUri.add(uri);
                        // Get the cursor
                        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                        // Move to first row
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        imageEncoded  = cursor.getString(columnIndex);
                        imagesEncodedList.add(imageEncoded);
                        cursor.close();

                    }
                    Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
                }
            }
        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

    super.onActivityResult(requestCode, resultCode, data);
}

答案 1 :(得分:1)

从api22到api29,这对我都有效。

Intent intent = new Intent();
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, HoiviaAppPermision.PICK_IMAGE);

然后在活动结果中添加该代码。

if (resultCode == RESULT_OK && requestCode == HoiviaAppPermision.PICK_IMAGE) {
            ClipData clipData = data.getClipData();
            if (clipData != null) {
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    Uri imageUri = clipData.getItemAt(i).getUri();
                    // your code for multiple image selection
                }
            } else {
              Uri uri = data.getData();
                // your codefor single image selection
            }

注意:进入图库屏幕后,请稍等图像。然后在右上角单击“打开”。它将允许您选择多个图像。

答案 2 :(得分:0)

试试这个:

public class MainActivity extends AppCompatActivity implements    View.OnClickListener {

  private static final int SELECT_PICTURE = 100;
  private static final String TAG = "MainActivity";

  CoordinatorLayout coordinatorLayout;
  FloatingActionButton btnSelectImage;
  AppCompatImageView imgView;


  @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);

   // Find the views...
   coordinatorLayout = (CoordinatorLayout)      findViewById(R.id.coordinatorLayout);
   btnSelectImage = (FloatingActionButton)  findViewById(R.id.btnSelectImage);
   imgView = (AppCompatImageView) findViewById(R.id.imgView);

   btnSelectImage.setOnClickListener(this);

   }

   /* Choose an image from Gallery */
   void openImageChooser() {
   Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),  SELECT_PICTURE);
  }

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
       if (requestCode == SELECT_PICTURE) {
        // Get the url from data
        Uri selectedImageUri = data.getData();
        if (null != selectedImageUri) {
            // Get the path from the Uri
            String path = getPathFromURI(selectedImageUri);
            Log.i(TAG, "Image Path : " + path);
            // Set the image in ImageView
            imgView.setImageURI(selectedImageUri);
             }
           }
         }
       }


     public String getPathFromURI(Uri contentUri) {
     String res = null;
     String[] proj = {MediaStore.Images.Media.DATA};
     Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
     if (cursor.moveToFirst()) {
       int column_index =   cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
      res = cursor.getString(column_index);
    }
    cursor.close();
    return res;
 }

   @Override
   public void onClick(View v) {
     openImageChooser();
    }
}

在清单文件中添加权限。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

答案 3 :(得分:0)

  

使用以下代码实现自定义图库选择器:   activity_main

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="@+id/scroll1"
>

<LinearLayout
    android:id="@+id/lnrImages"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="@+id/linearLayout">
<Button
    android:id="@+id/btnAddPhots"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:text="Add Phots"/>

<Button
    android:id="@+id/btnSaveImages"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:text="Save"/>

  

custom_gallery

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

  

customgalleryitem

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top|right"/>
  </FrameLayout>
  

MainActivityForGallery

public class MainActivity extends Activity implements View.OnClickListener{

private LinearLayout lnrImages;
private Button btnAddPhots;
private Button btnSaveImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE =1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lnrImages = (LinearLayout)findViewById(R.id.lnrImages);
    btnAddPhots = (Button)findViewById(R.id.btnAddPhots);
    btnSaveImages = (Button)findViewById(R.id.btnSaveImages);
    btnAddPhots.setOnClickListener(this);
    btnSaveImages.setOnClickListener(this);
}
@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btnAddPhots:
            Intent intent = new      Intent(MainActivity.this,CustomPhotoGalleryActivity.class);
            startActivityForResult(intent,PICK_IMAGE_MULTIPLE);
            break;
        case R.id.btnSaveImages:
            if(imagesPathList !=null){
                if(imagesPathList.size()>1) {
                    Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, imagesPathList.size() + " no of image are selected", Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(MainActivity.this," no images are selected", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if(requestCode == PICK_IMAGE_MULTIPLE){
            imagesPathList = new ArrayList<String>();
            String[] imagesPath = data.getStringExtra("data").split("\\|");
            try{
                lnrImages.removeAllViews();
            }catch (Throwable e){
                e.printStackTrace();
            }
            for (int i=0;i<imagesPath.length;i++){
                imagesPathList.add(imagesPath[i]);
                yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
                ImageView imageView = new ImageView(this);
                imageView.setImageBitmap(yourbitmap);
                imageView.setAdjustViewBounds(true);
                lnrImages.addView(imageView);
            }
        }
    }

}

}

  

CustomImageGalleryActivity

 public class CustomImageGalleryActivity extends Activity {

private GridView grdImages;
private Button btnSelect;

private ImageAdapter imageAdapter;
private String[] arrPath;
private boolean[] thumbnailsselection;
private int ids[];
private int count;


/**
 * Overrides methods
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.custom_gallery);
    grdImages= (GridView) findViewById(R.id.grdImages);
    btnSelect= (Button) findViewById(R.id.btnSelect);

    final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    @SuppressWarnings("deprecation")
    Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.arrPath = new String[this.count];
    ids = new int[count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i);
        ids[i] = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = imagecursor.getString(dataColumnIndex);
    }

    imageAdapter = new ImageAdapter();
    grdImages.setAdapter(imageAdapter);
    imagecursor.close();


    btnSelect.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            final int len = thumbnailsselection.length;
            int cnt = 0;
            String selectImages = "";
            for (int i = 0; i < len; i++) {
                if (thumbnailsselection[i]) {
                    cnt++;
                    selectImages = selectImages + arrPath[i] + "|";
                }
            }
            if (cnt == 0) {
                Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
            } else {

                Log.d("SelectedImages", selectImages);
                Intent i = new Intent();
                i.putExtra("data", selectImages);
                setResult(Activity.RESULT_OK, i);
                finish();
            }
        }
    });
}
@Override
public void onBackPressed() {
    setResult(Activity.RESULT_CANCELED);
    super.onBackPressed();

}

/**
 * Class method
 */

/**
 * This method used to set bitmap.
 * @param iv represented ImageView 
 * @param id represented id
 */

private void setBitmap(final ImageView iv, final int id) {

    new AsyncTask<Void, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(Void... params) {
            return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            iv.setImageBitmap(result);
        }
    }.execute();
}


/**
 * List adapter
 * @author tasol
 */

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return count;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.custom_gallery_item, null);
            holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
            holder.chkImage = (CheckBox) convertView.findViewById(R.id.chkImage);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.chkImage.setId(position);
        holder.imgThumb.setId(position);
        holder.chkImage.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                CheckBox cb = (CheckBox) v;
                int id = cb.getId();
                if (thumbnailsselection[id]) {
                    cb.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    cb.setChecked(true);
                    thumbnailsselection[id] = true;
                }
            }
        });
        holder.imgThumb.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                int id = holder.chkImage.getId();
                if (thumbnailsselection[id]) {
                    holder.chkImage.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    holder.chkImage.setChecked(true);
                    thumbnailsselection[id] = true;
                }
            }
        });
        try {
            setBitmap(holder.imgThumb, ids[position]);
        } catch (Throwable e) {
        }
        holder.chkImage.setChecked(thumbnailsselection[position]);
        holder.id = position;
        return convertView;
    }
}


/**
 * Inner class
 * @author tasol
 */
class ViewHolder {
    ImageView imgThumb;
    CheckBox chkImage;
    int id;
}

}

答案 4 :(得分:0)

要选择多个图像,我使用这个:

  1. 声明一个变量

    <块引用>

    ActivityResultLauncher activityResultLauncher;

2.在OnCreate方法中调用Register方法

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upload_ad_images);
    RegisterOpenImageDialog();
 }

3.这是注册方法

private void RegisterOpenImageDialog() {
        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.GetMultipleContents(), new ActivityResultCallback<List<Uri>>() {
            @Override
            public void onActivityResult(List<Uri> result) {
                if (result != null) {

                    int x = result.size();
                    
                    //Do What you Want Here ................
                    
                }
            }
        });
 }

4.当用户点击选择图片按钮时

private void btnSelectImage() {
     activityResultLauncher.launch("image/*");
}