有没有更简单的方法来编码以下要求并压缩代码?



我做了一个自定义的底栏。它有五张图片。选择特定图像时,将打开一个片段,所选图像将变为蓝色。其余的将保持黑色。 所以我现在正在做的是

img1,img2,img3,img4,img5

所以我将点击侦听器设置为它并像

@Override
public void onClick(View view) {
try {
switch (view.getId()) {
case R.id.img1:
// Set background image as blue to img1 and set //black for others
break;
case R.id.img2:
// Set background image as blue to img2 and set //black for others including the previous one
break;
case R.id.img3:
break;
case R.id.img4:
break;
case R.id.img5:
break;
}
} catch (Exception e) {
e.printStackTrace();
}

所以我一遍又一遍地重复步骤. 我可以将此代码压缩为更短的内容,例如将上一个图像存储在视图中并为当前图像着色?简而言之,压缩此代码的最佳方法是什么?

谢谢:)

您可以在try句子之前将所有图像的背景颜色设置为黑色,然后仅将所选图像的背景设置为蓝色:

@Override
public void onClick(View view) {
//Set black background for all the imags
try {
switch (view.getId()) {
case R.id.img1:
// Set background image as blue to img1 for others
break;

最新更新