So, I want to make a button which every time it gets pressed, it changes the image above the button. I have 2 images in total, so I don't use arrays. Let's say I have image1.png and image2.png. The default image is image1 and after I press the button it turns to image2. If I press it again it turns to image1.
package blablablabla;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.myicon);
}
public void onClick(View view) {
switch(view.getId()){
case R.id.button1:{
image.setImageResource(R.drawable.initial);
return;
}
}
}
}
I thought of making an if statment: if the image is image1, then change it to image2 and vice-versa.
The problem: after I change to image2, I can't switch back. I know I didn't write the code for that because I made it wrrong.
Ok i think this might do:
package blablablabla;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView image;
boolean flag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.myicon);
}
public void onClick(View view) {
switch(view.getId()){
case R.id.button1:{
if(flag)
{
image.setImageResource(R.drawable.initial);
flag=false;
}
else
{
image.setImageResource(R.drawable.secondary);
flag=true;
}
return;
}
}
}
}