Reputation: 109
my app has a bunch of xml layout files. now, i want to add a functionality where a defined number, i.e. 15, of them will be included in an activity. The 15 layouts should be picked randomly every time the activity is started. How do I do that? I was thinking about an array but could not find any good reference about how to include xml files in an array (random).
Upvotes: 1
Views: 748
Reputation: 39406
layout references are ints. you can simply choose one using :
int[] layouts = new int[] {R.layout.one, R.layout.two, R.layout.three ...};
setContentView(layouts[new Random().nextInt(layouts.length)]);
Upvotes: 6
Reputation: 5345
You could override Application.onCreate or in your main Activity.onCreate() and set the resource id of your desired layout in a SharedPreference.
public static final String LAYOUT_ID = "random.layout.id";
private static int[] LAYOUTS = new int[] { R.layout.default, R.layout.fancy };
public void onCreate() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putInt(LAYOUT_ID, getRandomLayoutId()).commit();
}
private int getRandomLayoutId() {
Random r = new Random(Calendar.getInstance().getTimeInMillis());
return LAYOUTS[r.nextInt(LAYOUTS.length)];
}
This id can then be used somewhere in your app with setContentView().
private static final int DEFAULT_ID = R.layout.default;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(getInt(MyApplication.LAYOUT_ID, DEFAULT_ID));
If you do it in your main Activity it may apply a new layout even on orientation changes or similar events.
Upvotes: 1