拿起画廊形象

时间:2012-04-14 20:25:52

标签: android eclipse image image-gallery

嗨,我对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”,我该怎么办。

1 个答案:

答案 0 :(得分:0)

由于Bitmap实现了Parcelable Interface,您可以直接通过intent发送它,因此请在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);
}  

并通过以下方式在Another Activity中读取此Bitmap对象:

Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");