Ardi
Ardi

Reputation: 53

Random layout XML in Android

I want to randomize my layout using this code:

public class testing extends Activity 
   {
    /** Called when the activity is first created. */
      private Integer [] mLinearLayoutIds = { 
            R.layout.games0,
            R.layout.games1,
            R.layout.games2,
            R.layout.games3,
            R.layout.games4,
            R.layout.games5,
            }; 
      public void onCreate(Bundle savedInstanceState) 
         {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
           Random random = new java.util.Random();
           int rand = random.nextInt(6);
           setContentView(mLinearLayoutIds[rand]);
         }
  }

but, every time the layout that was shown before is shown again.

How do I mark for a layout that has been shown before so it does not show again?

Upvotes: 1

Views: 979

Answers (2)

user1410657
user1410657

Reputation: 1294

I assume by “every time” you mean “next time activity is displayed after being in background”. I think you've placed code to the wrong method for this task. Try moving it out of void onCreate() to void onResume().

public class Testing extends Activity {
    private Integer [] mLinearLayoutIds = { 
        R.layout.games0,
        R.layout.games1,
        R.layout.games2,
        R.layout.games3,
        R.layout.games4,
        R.layout.games5,
    };

    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
    }

    public void onResume() {
        Random random = new java.util.Random();
        int rand = random.nextInt(6);
        setContentView(mLinearLayoutIds[rand]);
    }
}

Upvotes: 0

Edison
Edison

Reputation: 5971

This will require persistant storage. Refer to "SharedPreferences" to store your options for your layouts (Or if you have a lot, you can opt to use SQLite).

Every time when the user launch the activity, you should randomly pick an event from an array and store it as used and take it out of that array.

Doing it this way would require you to initialize the array the first time user has opened the app.

(You can do it with only one preference and store a string from a JSONArray that contain your choices.)

Upvotes: 2

Related Questions