Java/Android: How do I simplify this complicated, nested if else and for loop codeblock?
<p>I have two sections of code that are largely identical except for a few different constants that are used depending on the condition of the if statement. I would like to ask if anyone here knows how to simplify the code so that I don't have so much duplication of code.</p>

<p>Here's the code:</p>

<pre><code>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 &gt; screenHeight) {
    TableRow tableRow[] = new TableRow[numLandscapeRows];
    ImageView imageView[] = new ImageView[numLandscapeImagesPerRow];

    for (i = 0; i &lt; numLandscapeRows; i++) {
        for (j = 0; j &lt; 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 &lt; numPortraitRows; i++) {
        for (j = 0; j &lt; 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);
                        }
        }
    }
}
</code></pre>

<p>I hope that's easy to understand. My Java is very basic so I don't think I can write very complicated code. But if there's anything you need clarification on, please let me know.</p>

<p>Thank you for your time.</p>
