0

Hello I am a beginner learning Java I am trying to create a random image output The code I made stops with only one image coming out What I want is to keep showing the images at random Which code should I add? Please help me

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


        ImageView imageView_1 = findViewById(R.id.imageView_1);
      

        int[] images = {R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, R.drawable.img_4, R.drawable.img_5};

            Random rand = new Random();

            imageView_1.setImageResource(images[rand.nextInt(images.length)]);
        
        }
}
  • 2
    You want image to be changed for every few seconds ? Is that what you want ? – AgentP Jun 26 '20 at 04:45
  • You will need to write code that changes the image periodically. This may help: https://stackoverflow.com/questions/6425611/android-run-a-task-periodically – Henry Jun 26 '20 at 04:53
  • What I want to make is that the image changes randomly every second. – hyperion0205 Jun 26 '20 at 08:03

2 Answers2

1

Add this method first

 private Runnable showImageRandom=new Runnable() {
    @Override
    public void run() {

        Random rand = new Random();

        imageView.setImageResource(images[rand.nextInt(images.length)]);
        handler.postDelayed(this,2000);

    }
};

then add this handler in your OnCreate

 handler=new Handler();
 handler.postDelayed(showRandomImage,2000);

2000 is time delay

int[] images = {R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, 
 R.drawable.img_4, R.drawable.img_5};
 ImageView imageView_1;
 Handler handler;
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


     imageView_1 = findViewById(R.id.imageView_1);
    handler=new Handler();
    handler.postDelayed(showRandomImage,1000);
  

            
    }

private Runnable showImageRandom=new Runnable() {
 @Override
 public void run() {

    Random rand = new Random();

    imageView.setImageResource(images[rand.nextInt(images.length)]);
    handler.postDelayed(this,2000);

  }
  };

 
Yonatan
  • 150
  • 1
  • 9
0

Try this Hope this will work. You can print the randomNumber is generating or not.

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


        ImageView imageView_1 = findViewById(R.id.imageView_1);
      

        int[] images = {R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, R.drawable.img_4, R.drawable.img_5};

        int randomNumber = new Random().nextInt(images.length);
            

        imageView_1.setImageDrawable(getResources().getDrawable(images[randomNumber]));
        
        }
}
Noban Hasan
  • 593
  • 1
  • 7
  • 21