我有一个工作应用程序,但想优化代码。下面是一个示例,我创建了 10 个单独的图像按钮(注意每个按钮的递增对象名和 XML 引用)并设置它们的侦听器。任何人都可以提出一种更优化的方法,也许是动态方法/循环?谢谢....
private void initialiseButtons() {
ImageButton imageButton1 = (ImageButton)this.findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(this);
ImageButton imageButton2 = (ImageButton)this.findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(this);
ImageButton imageButton3 = (ImageButton)this.findViewById(R.id.imageButton3);
imageButton3.setOnClickListener(this);
ImageButton imageButton4 = (ImageButton)this.findViewById(R.id.imageButton4);
imageButton4.setOnClickListener(this);
ImageButton imageButton5 = (ImageButton)this.findViewById(R.id.imageButton5);
imageButton5.setOnClickListener(this);
ImageButton imageButton6 = (ImageButton)this.findViewById(R.id.imageButton6);
imageButton6.setOnClickListener(this);
ImageButton imageButton7 = (ImageButton)this.findViewById(R.id.imageButton7);
imageButton7.setOnClickListener(this);
ImageButton imageButton8 = (ImageButton)this.findViewById(R.id.imageButton8);
imageButton8.setOnClickListener(this);
ImageButton imageButton9 = (ImageButton)this.findViewById(R.id.imageButton9);
imageButton9.setOnClickListener(this);
ImageButton imageButton0 = (ImageButton)this.findViewById(R.id.imageButton0);
imageButton0.setOnClickListener(this);
}