0

嗨,我对 android 编程很陌生,这对某些人来说可能是一个简单的问题,但我对此很陌生。我想从一个意图打开画廊,但希望将挑选的图像显示在另一个意图上我使用了以下代码

public class GalActivity extends Activity {
    Context ctx;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView = (ImageView) findViewById(R.id.result);
    }

    private static final int REQUEST_CODE = 1;
    protected Bitmap bitmap;

    private ImageView imageView=null;

    /** Called when the activity is first created. */
    //  @Override

    public void pickImage(View View) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CODE);
    }

    // ctx=this;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
            try {
                // We need to recyle unused bitmaps
                if (bitmap != null) {
                    bitmap.recycle();
                }
                InputStream stream = getContentResolver().openInputStream(
                        data.getData());
                bitmap = BitmapFactory.decodeStream(stream);
                stream.close();

                imageView.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

如果要以相同的意图显示图像,则代码可以正常工作。但是如果它必须显示在另一个意图上,比如“activity2”,我该怎么办。

4

1 回答 1

0

由于 Bitmap 实现了 Parcelable 接口,您可以直接通过意图发送它,因此请在您的 onActivityResult 代码中执行以下操作:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
        try {
            // We need to recyle unused bitmaps
            if (bitmap != null) {
                bitmap.recycle();
            }
            InputStream stream = getContentResolver().openInputStream(
                    data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            stream.close();

          imageView.setImageBitmap(bitmap);

          Intent intent= new Intent(this, SecondActivity.class);
          intent.putExtra("BitmapImage", bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    super.onActivityResult(requestCode, resultCode, data);
}  

并通过以下方式在另一个活动中读取此位图对象:

Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
于 2012-04-14T20:49:58.930 回答