在 Android Studio 中加载多张图片时如何防止延迟

How to prevent lag when loading more than one picture in Android Studio

我需要从图库中获取 4 张图片...

当我触摸 Activity 中的 4 个 ImageView 之一时,它会调用以下代码:

public void imagePicker(View view)
{
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, view.getId());
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    ImageView image1=(ImageView)findViewById(R.id.image1);
    ImageView image2=(ImageView)findViewById(R.id.image2);
    ImageView image3=(ImageView)findViewById(R.id.image3);
    ImageView image4=(ImageView)findViewById(R.id.image4);

    if ((requestCode == R.id.image1 || requestCode == R.id.image2 || requestCode == R.id.image3 || requestCode == R.id.image4) && resultCode == RESULT_OK && data != null)
    {
        Uri pickedImage = data.getData();
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
        switch(requestCode)
        {
            case R.id.image1:
                image1.setImageBitmap(bitmap);
                break;
            case R.id.image2:
                image2.setImageBitmap(bitmap);
                break;
            case R.id.image3:
                image3.setImageBitmap(bitmap);
                break;
            case R.id.image4:
                image4.setImageBitmap(bitmap);
                break;
        }
        cursor.close();
    }

但是当它加载第二张图片时 Activity 开始滞后。 那么,我怎样才能避免这种情况呢?我想我可以降低 ImageView 的分辨率并将原始图像存储在其他地方。如果可行,我该怎么做?

尝试缩放 bitmap 以降低其实际分辨率,我使用以下代码来减小 bitmap 的大小。

int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);