Android基于listview位置在另一个活动中更改图像?

时间:2012-07-15 05:58:10

标签: java android eclipse listview imageview

我有一个包含100个左右项目的列表视图,每个项目在单击时打开另一个具有按钮和图像视图的活动。计划是为列表视图中的每个位置设置不同的图片。

所以,当用户点击列表视图中的项目以使其他活动中的imageview更改其图像时,我想知道你是否有任何方式? (来自drawable文件夹)

例如,

(if position == 1) {

     otheractivity imageview src = "pic 1;

}


(if position == 2) {

      otheractivity imageview src = "pic 2;

}

我真的不想做100个不同的活动。

3 个答案:

答案 0 :(得分:1)

在Intent中传递id。在List活动的onItemClick监听器中有以下内容:

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

然后在另一个Activity的onCreate中拉出来并设置它:

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

这是关于传递额外内容的另一篇SO帖子:How do I get extra data from intent on Android?

答案 1 :(得分:1)

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 );

答案 2 :(得分:0)

您可以使用intent.putExtra将ListView中所选行的位置发送到另一个活动:

@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); 
}
});

在第二项活动中:

//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
  }