Jessef Jessef - 6 months ago 33
Android Question

How to change the Imagerecource when Button is clicked

I want to click on an ImageView and when a certain amount of clickes is reached, I want the Imageview to change the image.
This is my code but I dont know where the problem is.
There is no error or something.
The Picture just doesnt change
Can you guys help me please.
Thanks

public class MainActivity extends AppCompatActivity {
private ImageView megg;
int counter = 0;
int readhighscore;
private TextView mnumber;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mnumber = (TextView) findViewById(R.id.number);
mnumber.setText(Integer.toString(readhighscore));
megg = (ImageView) findViewById(R.id.egg);
megg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter++;
readhighscore = counter;
mnumber.setText(Integer.toString(readhighscore));

}

});

if (counter == 10){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg100);

}

if (counter == 100){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg100);

}
if (counter == 500){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg500);

}


SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
counter = prefs.getInt("highscore", readhighscore);


}
@Override
protected void onPause() {
super.onPause();

SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("highscore", readhighscore);

editor.commit();

}
@Override
protected void onResume() {
super.onResume();SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
counter = prefs.getInt("highscore", readhighscore);
readhighscore = counter;
mnumber.setText(Integer.toString(readhighscore));
}
}

Answer Source

Put the flow statements inside the onClick method. Currently, If statements are outside of the OnClickListener and hence it will not get called on every click and you want to perform this check on every click.

 @Override
    public void onClick(View v) {
        counter++;
if (counter == 10){
    ImageView megg = (ImageView) findViewById(R.id.egg);
    megg.setImageResource(R.drawable.egg100);

}

if (counter == 100){
    ImageView megg = (ImageView) findViewById(R.id.egg);
    megg.setImageResource(R.drawable.egg100);

}
if (counter == 500){
    ImageView megg = (ImageView) findViewById(R.id.egg);
    megg.setImageResource(R.drawable.egg500);

}


    }

});