Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You cannot compare a Drawable with a Resource ID, which is what you are doing in:</p> <pre><code>if(img1.getBackground().equals(R.drawable.heart)){ ... </code></pre> <p>Maybe what you want is to save the Resource ID of the background when you set it, like:</p> <pre><code>this.mImg1Bg = R.drawable.heart; img1.setBackground(this.mImg1Bg); </code></pre> <p>And then on the onClick() you test with:</p> <pre><code>if(this.mImg1Bg == R.drawable.heart) { ... </code></pre> <p><strong>EDIT:</strong></p> <p>Now with the entire code it is easier.</p> <p>I will assume that you have this at the end of onCreate():</p> <pre><code>this.myImg1=R.drawable.heart; </code></pre> <p>just for testing purposes, as you are redefining it as it was set already.</p> <p>Now you have another problem with the string test. Shape variable is not what you want to test. Maybe if you test it like:</p> <pre><code>public void onClick(View v){ String txt = ((Button)v).getText(); if(txt.equals("Heart")){ if(myImg1 == R.drawable.heart){ correct++; } } ... } </code></pre> <p>I don't know what exactly you are showing in your Activity, but it seems to me that you could simplify a lot if you used:</p> <pre><code>HashMap&lt;String, Integer&gt; shapes; shapes.put("Heart", R.drawable.heart); ... </code></pre> <p>to store the shapes strings and relation to resources.</p> <p>An ArrayList of Pair's to store the combinations on the buttons:</p> <pre><code>ArrayList&lt;Pair&lt;Integer,String&gt;&gt; buts; buts.add(new Pair&lt;Integer,String&gt;(R.drawable.heart, "Heart")); ... </code></pre> <p>Set a tag on each button view to know which button number was clicked:</p> <pre><code>img1.setTag(1); ... </code></pre> <p>Then assign the same OnClickListener to all buttons. For instance by implementing the interface by your Activity, like:</p> <pre><code>public class Game extends Activity implements OnClickListener { ... img1.setOnClickListener(this); ... </code></pre> <p>And check the onClick() like this:</p> <pre><code> public void onClick(View v) { int res = buts.get((Integer)v.getTag()).first; String txt = buts.get((Integer)v.getTag()).second; if(res == shapes.get(txt)) { correct++; } } </code></pre> <p>And then don't forget to assign the correct to some UI TextView so you can view the result.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload