【问题标题】:Dynamically created ImageButtons not visible动态创建的 ImageButtons 不可见
【发布时间】:2014-09-19 13:38:25
【问题描述】:

我正在尝试创建一个 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);
}

【问题讨论】:

  • 那么您必须设置布局参数并添加您想要的图像??
  • 您需要设置按钮的宽度和高度。
  • 我认为您将无法使用LinearLayout 做您想做的事情,请尝试使用FrameLayout
  • 在ScrollView中采用垂直方向的LinearLayout。

标签: java android imagebutton


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-27
    • 2018-09-07
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 2020-08-13
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多