简体   繁体   中英

Random array is called again when orientation changes in android

I want to display some random sentence in my app. Since that piece of code is inside onCreate method , it is getting called each time the orientation of the app changes.

Here is my code for generating random list of array inside Oncreate method

      int listlen = list.size(); // get the size and gen the random index
     System.out.println("len" + listlen);
     Random indexval = new Random();
    int n = indexval.nextInt(listlen); // get random val
    System.out.println("random num " + n);

I couldn't add this below line of code in my app

    android:configChanges="orientation|screenSize|keyboardHidden"

because I am calculating the screen size manually when orientation changes and also due to some other issues I removed the above line of code. So , is it possible to generate the random list whenever the app opens ? Because I get different random words when orientation changes. Any help would be great !! Thanks

WHen you rotate, unless that configChanges line is in the manifest, the entire Activity will get killed and restarted from onCreate. If you want to ensure you use the same three words, save them in onSaveInstanceState and in either onCreate or in onRestoreInstanceState grab them from the bundle.

你可以在你的 Application 类中完成它,在 onCreate()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM