我正在为我的应用动态创建按钮,我想将它们随机放在屏幕上。
我尝试使用线性布局方法setMargins
来定位它们:
按钮创建位于onCreate
:
// Create buttons
for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {
Button hiddenButton = new Button(this);
// Set new button properties
hiddenButton.setId(i);
hiddenButton.setOnClickListener(setOnClick(hiddenButton));
// Add the button to the array of buttons
buttonsArr[i] = hiddenButton;
}
我有这个函数随机放置它们:
private void placeButtonsOnScreen() {
Random r = new Random();
LinearLayout layout = (LinearLayout) findViewById(R.id.ordered_buttons_layout);
for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {
final Button hiddenButton = buttonsArr[i];
// Get random horizontal margin for the button
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
horizontalMargin = r.nextInt(Math.abs(SCREEN_WIDTH
- hiddenButton.getWidth()));
layoutParams.setMargins(horizontalMargin, 50, 0, 0);
// Add the button to the screen
layout.addView(hiddenButton, layoutParams);
Log.d("button width", String.valueOf(hiddenButton.getWidth()));
}
}
问题是getWidth()
函数返回0.我应该怎么做才能将按钮放在屏幕上而不会被屏幕两侧切掉(即减去按钮的宽度)?
答案 0 :(得分:0)
您只能在布局传递后获取视图尺寸,因此您调用placeButtons而不是调用:
getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
placeButtons();
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
更新:
int btnCount = 10;
final LinearLayout layout = (LinearLayout) findViewById(R.id.action_bar);
for (int i = 0; i < btnCount; i++) {
layout.addView(new Button(this),new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
layout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
for(int i = 0; i<layout.getChildCount(); i++) {
View view = layout.getChildAt(i);
if(view instanceof Button) {
LinearLayout.LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
int horizontalMargin = r.nextInt(Math.abs(SCREEN_WIDTH - view.getWidth()));
layoutParams.setMargins(horizontalMargin, 50, 0, 0);
view.setLayoutParams(layoutParams);
}
}
}
});
layout.requestLayout();