So what I want to achieve is to change the position of my buttons. this is my sample picture:
Note:
My buttons have background drawable, for example sake, I just uploaded without the background images on buttons.
Default
When shuffled:
So this is the code I'm working on:
List<Integer> objects = new ArrayList<Integer>();
objects.add(0);
objects.add(1);
objects.add(2);
objects.add(3);
objects.add(4);
// Shuffle the collection
Collections.shuffle(objects);
List<Button> buttons = new ArrayList<Button>();
buttons.add((Button) findViewById(R.id.bObject1Stage2_1));
buttons.add((Button) findViewById(R.id.bObject2Stage2_1));
buttons.add((Button) findViewById(R.id.bObject3Stage2_1));
buttons.add((Button) findViewById(R.id.bObject4Stage2_1));
buttons.add((Button) findViewById(R.id.bObject5Stage2_1));
Collections.shuffle(buttons);
for (int i = 0; i < objects.size(); i++) {
//buttons.get(i).setText(objects.get(i).toString());
buttons.get(i);
}
But it's not changing the position of buttons. What am I missing in here? Any help is truly appreciated. Thanks.
Use RelativeLayout.LayoutParams to switch values between buttons You wish to move and apply them using setLayoutParams method
This will allow You to switch position of 2 buttons. To shuffle them You have to prepare some algorithm to make number of switches.
RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) b1.getLayoutParams();
RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) b2.getLayoutParams();
b1.setLayoutParams(params2);
b2.setLayoutParams(params1);
This will work only if these button are not relative to each other. If for example b2 was relative to b1 so it is below it You would have to set b1 to be below b1 using addRule method and removeRule on b2 so it is not relative to b1 any more.
for example You have in xml
<Button
android:id="@+id/bObject2Stage2_1"
/*...*/
android:layout_toRightOf="@+id/bObject1Stage2_1" />
to set this rule You would write
params.addRule(RelativeLayout.RIGHT_OF, R.id.bObject1Stage2_1);
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.