Adil Chaudhry
Adil Chaudhry

Reputation: 289

Android change image in another activity based on listview posistion?

I have a listview with 100 or so items, each when clicked opens another activity which has a button and an imageview. The plan is to have a different picture for each position in the listview.

So, I was wondering is thee any way when the user clicks an item in the listview to have the imageview in the other activity change its image ? (from drawable folder )

eg,

(if position == 1) {

     otheractivity imageview src = "pic 1;

}


(if position == 2) {

      otheractivity imageview src = "pic 2;

}

I really dont want to make 100 different activities.

Upvotes: 0

Views: 1724

Answers (3)

Avi Kumar
Avi Kumar

Reputation: 4433

Rather using if else condition make array of drawable which will be easy to use like

int[] myImageList = new int[]{R.drawable.thingOne, R.drawable.thingTwo};

and on list item click send the intent like

@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long id) {
        // TODO Auto-generated method stub

        // game_count
            Intent b = new Intent(Configure_Game_List.this, UpdateGame.class);
        b.putExtra("Name", myImageList.get [position]);
        b.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        finish();
        startActivity(b);


    } 


and recieve it as

int imageID = getIntent().getIntExtra("Name", 1);

and set the image 
as


myImageView.setImageResource(imageID );

Upvotes: 1

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

You can send position of selected row in ListView to another Activity using intent.putExtra as:

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    long arg3) {
    // TODO Auto-generated method stub
Intent intent = new Intent();  
intent.setClass(ListActivityw.this,SecondActivity.class);
intent.putExtra("position",Integer.toString(arg2));  
ListActivityw.this.startActivity(intent); 
}
});

In Second Activity:

//obtain  Intent Object send  from SenderActivity
  Intent intent = this.getIntent();
  /* Obtain String from Intent  */
  if(intent !=null)
  {
     String position  = intent.getExtras().getString("position");
    (if position == "1") {
       imageview src = "pic 1;
     }
     ///your code here
  }
  else
  {
    // DO SOMETHING HERE
  }

Upvotes: 0

Salil Pandit
Salil Pandit

Reputation: 1498

Pass the id in the Intent. In your List Activity's onItemClick listener have the following:

startActivity(new Intent(this, DisplayImageActivity.class).putExtra("imageId", clickedImageId)); //clickedImageId should be R.drawable.my_pic_20 or something

Then in the other Activity's onCreate just pull it out and set it:

onCreate {
  final int imageId = getIntent().getExtra("imageId");
  imageView.setImageResource(imageId);
  ...
}

Here is another SO post on passing extras: How do I get extra data from intent on Android?

Upvotes: 1

Related Questions