将图像/图片作为参数传递给android studio中的函数?

时间:2016-06-23 21:41:43

标签: java android function android-drawable imagebutton

如何将图像/图片作为参数传递给android studio中的函数?

我在drawable文件夹中有pic1.jpg,pic2.jpg,pic3.jpg和pic4.jpg,我有类似的东西:

private void exampleFunction() {
   ImageButton key1 = (ImageButton) findViewById(com.example.game.R.id.key1);
   ImageButton key2 = (ImageButton) findViewById(com.example.game.R.id.key2);
   ImageButton key3 = (ImageButton) findViewById(com.example.game.R.id.key3);
   ImageButton key4 = (ImageButton) findViewById(com.example.game.R.id.key4);

   if ( condition1) {
    key1.setImageResource(com.example.game.R.drawable.pic1);
    key2.setImageResource(com.example.game.R.drawable.pic2);
   } 
   else if ( condition2 ) {
        key3.setImageResource(com.example.game.R.drawable.pic3);
        key4.setImageResource(com.example.game.R.drawable.pic4);
   }
}

我怎么能这样做:

private void exampleFunction() {
   ImageButton key1 = (ImageButton) findViewById(com.example.game.R.id.key1);
   ImageButton key2 = (ImageButton) findViewById(com.example.game.R.id.key2);
   ImageButton key3 = (ImageButton) findViewById(com.example.game.R.id.key3);
   ImageButton key4 = (ImageButton) findViewById(com.example.game.R.id.key4);
   if ( condition1) {
       assignPics (key1, key2, pic1, pic2);
   } 
   else if ( condition2 ) {
       assignPics (key3, key4, pic3, pic4);
   }    
}


private void assignPics( ImageButton p1, ImageButton p2, ...how should I receive picture1-2 here ) {
     p1.setImageResource( ?? picture1 ?? );
     p2.setImageResource( ?? picture2 ?? );
}

2 个答案:

答案 0 :(得分:0)

如果imgkey表示你的img的关键,如pic1,pic2等,你知道关键,然后试试这个。 K =((ImageButton的)视图).setImageResource(R.drawable.imgkey);使用此选项可将图片指定给图像按钮。希望这可以帮助。 :)

答案 1 :(得分:0)

Android中的ID为int值,因此assignPics函数应如下所示:

private void assignPics(ImageButton p1, ImageButton p2, int id1, int id2) {
    p1.setImageResource(id1);
    p2.setImageResource(id2);
}