2014-09-19 44 views
1

我试图创建一个ImageButtons数组,这些ImageButtons都是随机选择的3个图像之一显示在屏幕的边界内。问题是大多数按钮出现在屏幕外/根本不显示。我在运行时检查了坐标,它们都在屏幕的边界内,但我看不到图像。大多数时候我能看到一个,有时两个。总共应该有12个。动态创建ImageButtons不可见

宽度和高度是在onCreate()中计算的屏幕度量,其中还调用了createBalloons()。图像[]数组包含drawable的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); 
} 
+0

那么你必须设置布局参数并添加图像你想要什么? – 2014-09-19 05:31:54

+0

你需要设置Widht和你的按钮的高度。 – Techfist 2014-09-19 05:34:21

+0

我认为你不能用'LinearLayout'来做你想要的,用'FrameLayout'来代替。 – zozelfelfo 2014-09-19 05:36:02

回答

0

与此

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); 
} 

而且取代setUpballons,为u提到的12个按键也纯属偶然您的布局不会成为持有所有的人,可以尝试设置滚动型父的LinearLayout中。