ANDROID - 2 different intents opens the same activ

2019-08-31 14:35发布

问题:

I'm making an app and at this point i have two different intents carrying images. I' am trying to pass those images in the same activity in imageViews.

Can anyone help? Thanks!!

My code is:

ImageButton btn_insert = (ImageButton)findViewById(R.id.btn_insert);
    btn_insert.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i  = new Intent(getApplicationContext(), ViewClothes.class);
            i.putExtra(ITEM_IMAGE1, image1);
            startActivity(i);

            Intent i2 = new Intent(getApplicationContext() , ViewClothes.class);
            i2.putExtra(ITEM_IMAGE2 , image2);
            startActivity(i2);


        }
    });

And in the second activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.view_clothes);

    Intent i = getIntent();
    ImageView image1 = (ImageView)findViewById(R.id.im1);
    image1.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image1")));

    Intent i2 = getIntent();
    ImageView image2 = (ImageView)findViewById(R.id.im2);
    image2.setImageBitmap(BitmapFactory.decodeFile(i2.getStringExtra("image2")));



}

回答1:

You dubbled the Intent and you launched the next Activity twice.

A single Intent can have multiple objects and pass those to an Activity. One Intent is used to launch the next Activity but you can easily add several objects with it as follows:

// first activity
Intent i = new Intent(getApplicationContext(), ViewClothes.class);
i.putExtra(ITEM_IMAGE1, image1);
i.putExtra(ITEM_IMAGE2 , image2);
startActivity(i);

And received all images like:

// next activity
ImageView image1 = (ImageView)findViewById(R.id.im1);
ImageView image2 = (ImageView)findViewById(R.id.im2);

Intent i = getIntent();
image1.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra(ITEM_IMAGE1)));
image2.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra(ITEM_IMAGE2)));

Another solution might be to use a StringArray for your several images. In the first Activity, you could populate the array:

// populate the array
String[] images = new String[] { image1, image2 };
// pass the array
Intent i = new Intent(getApplicationContext(), ViewClothes.class);
i.putExtra(ARRAY_IMAGES, images);

And pass into the Intent to retrieve it like this:

// retrieve it
String[] images_passed = getIntent().getStringArrayExtra(ARRAY_IMAGES);
// show the images
image1.setImageBitmap(BitmapFactory.decodeFile(images_passed[0]));
image2.setImageBitmap(BitmapFactory.decodeFile(images_passed[1]));