我正在尝试创建一个 ImageButton 数组,这些按钮全部显示在屏幕范围内,并随机选择 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 的父级。
关于java - 动态创建的 ImageButtons 不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25926922/