动态创建的ImageButtons不可见

时间:2014-09-19 05:24:20

标签: java android imagebutton

我试图创建一个ImageButtons数组,这些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);
}

1 个答案:

答案 0 :(得分:0)

用此

替换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的父级。