[英]Exchange the position of button in android
因此,我要实现的是更改按钮的位置。 这是我的示例图片:
注意:
我的按钮具有可绘制的背景,例如,我只是上传了按钮而没有背景图像。
默认
随机播放时:
这是我正在处理的代码:
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);
}
但这并没有改变按钮的位置。 我在这里想念什么? 任何帮助,我们都感激不尽。 谢谢。
使用RelativeLayout.LayoutParams在按钮之间切换值您希望使用setLayoutParams方法移动和应用它们
这将允许您切换2个按钮的位置。 要对其进行混洗,您必须准备一些算法来进行多个开关。
RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) b1.getLayoutParams();
RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) b2.getLayoutParams();
b1.setLayoutParams(params2);
b2.setLayoutParams(params1);
仅当这些按钮彼此不相关时,这才起作用。 例如,如果b2是相对于b1的,那么它就在b1之下。您必须使用addRule方法并在b2 上将removeRule设置为b1在b1之下,以便它不再相对于b1。
例如您在xml中
<Button
android:id="@+id/bObject2Stage2_1"
/*...*/
android:layout_toRightOf="@+id/bObject1Stage2_1" />
设置这个规则,你会写
params.addRule(RelativeLayout.RIGHT_OF, R.id.bObject1Stage2_1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.