[英]Dynamically created ImageButtons not visible
我正在尝试创建一个ImageButtons数组,它们全部显示在屏幕的边界内,并随机选择3个图像之一。 问题是大多数按钮不在屏幕上显示/根本不显示。 我已经在运行时检查了坐标,它们都在屏幕的范围内,但是我看不到图像。 大多数时候,我能够看到一个,有时看到两个。 总共应该有12个。
宽度和高度是在onCreate()中计算的屏幕指标,其中还调用了createBalloons()。 images []数组包含可绘制对象的ID。
private void createBalloons() {
LinearLayout layout = (LinearLayout)findViewById(R.id.container);
for (int i = 0; i < GameActivity.MAX_BALLOONS; i++) {
balloons[i] = new ImageButton(this);
setupBalloon(balloons[i], i);
layout.addView(balloons[i]);
}
}
private void setupBalloon(ImageButton b, int i) {
int imageId = (int)(Math.random() * images.length);
b.setImageResource(images[imageId]);
b.setBackgroundColor(Color.TRANSPARENT);
b.setScaleX(0.4f);
b.setScaleY(0.4f);
b.setX((float) (Math.random() * (width - b.getWidth())));
b.setY((float) (Math.random() * (height - b.getHeight())));
b.setVisibility(View.VISIBLE);
}
以此替换setUpballons
private void setupBalloon(ImageButton b, int i) {
int imageId = (int)(Math.random() * images.length);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
b.setLayoutParams(params);
b.setImageResource(images[imageId]);
b.setBackgroundColor(Color.TRANSPARENT);
b.setScaleX(0.4f);
b.setScaleY(0.4f);
b.setX((float) (Math.random() * (width - b.getWidth())));
b.setY((float) (Math.random() * (height - b.getHeight())));
b.setVisibility(View.VISIBLE);
}
另外,如您提到的12个按钮,您的布局很有可能无法全部容纳,请尝试将ScrollView设置为LinearLayout的父级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.