正如您从两张图片中看到的那样,我正在尝试添加一组用户可以玩的可点击式磁贴。为了使这些图像可以处理,我决定使用这个calculator app的switch语句。 有没有办法将与这些图块有关的switch语句转换为循环或函数,而不是这个神奇可怕的长代码? 也许是这样的?
onTapped(arg0.getId, [R.id.tile1, R.id.tile2, R.id.tile3, R.id.tile4, R.id.tile5, R.id.tile6, R.id.tile7], ['l','e','a','s','t')
onTapped(id, listOfTiles, listOfLetters){
int i = 0;
for each tile:
if (!tile1_flag) {
str = str.append(listOfLetters[i++]);
disp.setText(str);
tile1.setColorFilter(Color.argb(150, 200, 200, 200));
tile1_flag = true;
break;
这是原始功能。
boolean tile1_flag = false;
boolean tile2_flag = false;
boolean tile3_flag = false;
boolean tile4_flag = false;
boolean tile5_flag = false;
boolean tile6_flag = false;
boolean tile7_flag = false;
.
.
.
public void onClick(View arg0) {
TextView disp = (TextView) findViewById(R.id.tileOutput);
Editable str = (Editable) disp.getText();
switch (arg0.getId()) {
case R.id.tile1:
if (!tile1_flag) {
str = str.append('l');
disp.setText(str);
tile1.setColorFilter(Color.argb(150, 200, 200, 200));
tile1_flag = true;
break;
} else {
break;
}
case R.id.tile2:
if (!tile2_flag) {
str = str.append('e');
disp.setText(str);
tile2.setColorFilter(Color.argb(150, 200, 200, 200));
tile2_flag = true;
break;
} else {
break;
}
case R.id.tile3:
if (!tile3_flag) {
str = str.append('a');
disp.setText(str);
tile3.setColorFilter(Color.argb(150, 200, 200, 200));
tile3_flag = true;
break;
} else {
break;
}
case R.id.tile5:
if (!tile5_flag) {
str = str.append('s');
disp.setText(str);
tile4.setColorFilter(Color.argb(150, 200, 200, 200));
tile4_flag = true;
break;
} else {
break;
}
case R.id.tile6:
if (!tile6_flag) {
str = str.append('t');
disp.setText(str);
tile4.setColorFilter(Color.argb(150, 200, 200, 200));
tile4_flag = true;
break;
} else {
break;
}
答案 0 :(得分:1)
您可以使用所有图像属性创建内部类,例如
class ImageProperties {
public boolean titleFlag;
public String appendLetter;
...
ImageProperties(boolean titleFlag, String appendLetter, ...) {
this.titleFlag = titleFlag;
...
}
}
然后填充它们作为标记添加到相应的图像,例如
ImageView title1 = (ImageView) findViewById(R.id.title1);
title1.setTag(new ImageProperties(false, "l"))
最后让他们进入
public void onClick(View arg0) {
ImageView imageView = (ImageView) arg0;
ImageProperties imageProperties = (ImageProperties) arg0.getTag();
if (!imageProperties.titleFlag) {
str = str.append(imageProperties.appendLetter);
disp.setText(str);
imageView.setColorFilter(Color.argb(150, 200, 200, 200));
imageProperties.titleFlag = true;
}
}