【发布时间】:2015-10-29 07:04:39
【问题描述】:
我正在开发一个需要动态创建多个按钮的应用程序(MainActivity 类的 onCreate)。每个按钮的尺寸为 100x100dp。
代码如下:
for (int i = 0; i < count; i++) {
buttons[i] = new Button(this);
RelativeLayout ll = (RelativeLayout)findViewById(R.id.maincontainer);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
buttons[i].setY(i * 150); // should be random
buttons[i].setX(i * 120); // should be random
String temp = Character.toString(input.charAt(i));
buttons[i].setText(temp);
buttons[i].setOnClickListener(this);
buttons[i].setId(i);
test1.setText(Integer.toString(buttons[i].getId()));
ll.addView(buttons[i],lp);
}
这些按钮的位置在布局中应该是完全随机的,这可以通过为 x 和 y 坐标生成随机值来轻松实现。但我需要按钮不要与其他按钮重叠。此外,由于 100x100dp 尺寸,有时以前生成的按钮会被新按钮部分重叠。
【问题讨论】: