gpt4 book ai didi

Java/Android : How do I simplify this complicated, 嵌套 if else 和 for 循环代码块?

转载 作者:行者123 更新时间:2023-12-02 00:42:49 25 4
gpt4 key购买 nike

我有两段代码,除了根据 if 语句的条件使用的一些不同的常量之外,它们基本上是相同的。我想请问这里有没有人知道如何简化代码,这样我就不会出现那么多重复的代码。

代码如下:

public static final int numLandscapeRows = 5;
public static final int numPortraitRows = 8;
public static final int numLandscapeImagesPerRow = 8;
public static final int numPortraitImagesPerRow = 5;
public static boolean imageViewLandscapeTracker[][] = new boolean[numLandscapeRows][numLandscapeImagesPerRow];
public static boolean imageViewPortraitTracker[][] = new boolean[numPortraitRows][numPortraitImagesPerRow];

if (screenWidth > screenHeight) {
TableRow tableRow[] = new TableRow[numLandscapeRows];
ImageView imageView[] = new ImageView[numLandscapeImagesPerRow];

for (i = 0; i < numLandscapeRows; i++) {
for (j = 0; j < numLandscapeImagesPerRow; j++) {
imageView[j].setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if (imageViewLandscapeTracker[i-1][j-1] == false) {
imageViewLandscapeTracker[i-1][j-1] = true;
v.setBackgroundResource(R.drawable.launcher);
} else {
imageViewLandscapeTracker[i-1][j-1] = false;
v.setBackgroundResource(R.drawable.icon);
}
}
}

} else {
TableRow tableRow[] = new TableRow[numPortraitRows];
ImageView imageView[] = new ImageView[numPortraitImagesPerRow];

for (i = 0; i < numPortraitRows; i++) {
for (j = 0; j < numPortraitImagesPerRow; j++) {
imageView[j].setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if (imageViewPortraitTracker[i-1][j-1] == false) {
imageViewPortraitTracker[i-1][j-1] = true;
v.setBackgroundResource(R.drawable.launcher);
} else {
imageViewPortraitTracker[i-1][j-1] = false;
v.setBackgroundResource(R.drawable.icon);
}
}
}
}

我希望这很容易理解。我的Java非常基础,所以我不认为我可以编写非常复杂的代码。但如果您有任何需要澄清的地方,请告诉我。

感谢您的宝贵时间。

最佳答案

似乎你可以创建一个简单的函数来完成这项工作(这个语法不是 100% 正确,但你应该明白):

reducedFunction(int numRows, int numImages, bool[][] tracker) {
for (i = 0; i < numRows; i++) {
for (j = 0; j < numImages; j++) {
imageView[j].setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if (tracker[i-1][j-1] == false) {
tracker[i-1][j-1] = true;
v.setBackgroundResource(R.drawable.launcher);
} else {
tracker[i-1][j-1] = false;
v.setBackgroundResource(R.drawable.icon);
}
}
}
}

if(screenWidth > screenHeight) {
reducedFunction(numLandscapeRows, numLandscapeImagesPerRow, imageViewLandscapeTracker)
}
else {
reducedFunction(numPortraitRows, numPortraitImagesPerRow, imageViewPortraitTracker)
}

关于Java/Android : How do I simplify this complicated, 嵌套 if else 和 for 循环代码块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5873042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com