When you click on the button (btnNext) in the ImageView , the picture should change, in fact, the code is working, but there is a problem. When I click on this button, my activation is recreated and therefore the array starts working from the very beginning. Is there a solution to this problem?

 Button btnNext = (Button) dialog.findViewById(R.id.btnNext); final int[] images = { R.drawable.p_reset, R.drawable.pic, }; btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dialog.dismiss(); finish(); startActivity(getIntent()); ImageView imageView = (ImageView) findViewById(R.id.imageView); imageView.setImageResource(images[0]); } }); 
  • one
    Why recreate to change the picture? - temq
  • @temq activations are re-created with a different purpose to change the content - A.Schtolc
  • @A.Schtolc, as I understand it, you need to maintain the position in the array after the activation start? Those. if there was 1 at the completion, then after the re-creation there should be 1? - JuriySPb ♦
  • @YuriSpb Yes, you are right - A.Schtolc

1 answer 1

There are several options for how to save some data in the activation so that it will be restored during the re-creation.

If you modify your code, in which you do not recreate the activation, but restart, then the desired value can be placed in the Bundle intensity, with which you activate the restart. Those. something like this:

 finish(); Intent intent = getIntent(); Bundle b = new Bundle(); b.putInt("KEY_POSITION", position); intent.putExtras(b); startActivity(intent); 

After that, when the so-activated activation starts, you can pull out the recorded value like this:

 int position = getIntent().getExtras().getInt("KEY_POSITION"); 

In general, it is better to do this:

  1. Do not restart the activation, but recreate using the recreate() method
  2. Override the onSaveInstanceState() method and in it, by analogy with the code above, save the values ​​of the variable position . This method will be called automatically when recreating the activation (for example, when you rotate the screen)
  3. In the onCreate(Bundle savedInstanceState) method onCreate(Bundle savedInstanceState) , Bundle will come as an argument where it will be the value written in the onSaveInstanceState() method, onSaveInstanceState() will be pulled out by analogy with the code above.
  • And the option of changing the picture after the re-creation of the activation is possible? - A.Schtolc
  • @ A.Schtolc, of course. On the vskidku, it is possible, having received from the Bundle value to generate a random number until it is equal to the recorded one. So you always get a new picture when recreating. - Yuriy SPb ♦