如何将一个图像按钮作为参数传递给android studio中的函数?

时间:2016-06-09 18:23:32

标签: java android function imagebutton

我的应用程序中有一些图像按钮,它们显示的图像是在代码中确定的(它们不应该响应触摸/点击)。如何将图像按钮作为参数传递给android studio中的函数?我是这样做的:

private void compute_progress() {
   ...  
   progress_1();
   progress_2();
   ...
   progress_10();
   ...
}

private void progress_1() {
   ImageButton p1 = (ImageButton) findViewById( R.id.Progress1 );
   ...
   p1.setImageResource ( R.drawable.picture );
   ...
}

private void progress_2() {
   ImageButton p2 = (ImageButton) findViewById( R.id.Progress2 );
   ...
   p2.setImageResource ( R.drawable.picture );
   ...
}

...

private void progress_10() {
   ImageButton p10 = (ImageButton) findViewById( R.id.Progress10 );
   ...
   p10.setImageResource ( R.drawable.picture );
   ...
}

但我应该并且想要这样做:

private void compute_progress() {
   ImageButton p1 = (ImageButton) findViewById( R.id.Progress1 );
   ImageButton p2 = (ImageButton) findViewById( R.id.Progress2 );
   ...
   ImageButton p10 = (ImageButton) findViewById( R.id.Progress10 );

   ...

   progress("imagebutton p1");
   progress("imagebutton p2");
   ...
   progress("imagebutton p10");

   ...
}

private void progress("receive ImageButton p") {
   ...
   p.setImageResource ( R.drawable.picture );
   ...
}

1 个答案:

答案 0 :(得分:2)

将您希望接收private void progress(ImageButton imgButton) { imgButton.setImageResource(R.drawable.picture) } 的方法定义为参数,如下所示:

ImageButton

然后当你需要调用你的方法时,请这样称呼它(P1是你的progress(p1)

{{1}}