I got a tutorial about using a button for switching some images, and here is the code
public class MainActivity extends AppCompatActivity {
private static ImageView andro;
private static Button buttonswitch;
int current_image_index = 0;
int[] images = {R.mipmap.andro_img,R.mipmap.apple_image,R.mipmap.ic_launcher,R.mipmap.ic_launcher_round};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
}
public void buttonClick() {
andro = (ImageView) findViewById(R.id.imageView);
buttonswitch = (Button) findViewById(R.id.button);
buttonswitch.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
current_image_index++;
current_image_index = current_image_index % images.length;
andro.setImageResource(images[current_image_index]);
}
}
);
}
}
I got really confused in this part :
@Override
public void onClick(View view) {
current_image_index++;
current_image_index = current_image_index % images.length;
andro.setImageResource(images[current_image_index]);
What I understand is that once I click the button, then the int current_image_index will increase by 1. Then modulus current_image_index with the images.length which will have the remainder of current_image_index divide by the image.length. For example, for the first time I will have current_image_index = 0, then once clicked, it will be 1, then current_image_index % image.length = 0. Then andro.setImageResource(images[0]);
this will repeated again and again since the current_image_index stays to be 0. Then how can the picture changes constantly once it is clicked since the current_image_index%image.length will always give a result of 0.