Search code examples
javaandroidxmlbackgroundlauncher

how to setup multiple background on one activity randomly


i need to know how to setup background randomly on one activity, 'android:background="@drawable/backG"' only show one image the background come randomly with the launch of the application, and it keep on showing until the user quit the app, and when he reopen it, it will show a new background note : i have only one activity in my project thanks in advance


Solution

  • I think, you should use Java code to make this.
    For example, you have RelativeLayout is the main layout in your activity
    You should use

    RelativeLayout rLayout = (RelativeLayout) findViewById (R.id.rLayout);
    Resources res = getResources(); //resource handle
    Drawable drawable = res.getDrawable(R.drawable.newImage); //new Image that was added to the res folder
    rLayout.setBackground(drawable);
    

    For random background: you create an array that contains all you images background and use the code below for random position

    Random randomGenerator = new Random();
    int randomPositionInt = randomGenerator.nextInt(10); // it will generate position in 0 - 10
    

    Hope this help