在开始时将随机位置设置为ImageView

时间:2012-04-14 19:09:31

标签: java android layout imageview

我的RelativeLayout上有8个ImageView。 当活动onCreate它启动方法init:

 private void init() {
        gameFieldView = (RelativeLayout) getGameFieldView();
        mainView = (LinearLayout) getMainView();
        topOffset = mainView.getHeight() - gameFieldView.getHeight() - 6;
        // THERE ARE 0 height and width of gameFieldView, and mainView 
        for (int i = 0; i < LETTERS_NUMBER; i++) {
            ImageView letter = (ImageView) findViewById(R.id.e1_letter + i);
            generateRandomPosition(random, letter); // When i comment this line it is ok (What kind of sorcery is this?), but i want to set random position to ImageView "letter"
        }
    }

现在generateRandomPosition看起来像

private void generateRandomPosition(Random random, ImageView letter) {
        int height = letter.getHeight();
        int width = letter.getWidth();
        int top = random.nextInt(gameFieldView.getMeasuredHeight() - height - topOffset); // It obviously crashes because of IllegalArgumentException - parameter < 0 because of gameFieldView height = 0 
        int left = random.nextInt(gameFieldView.getMeasuredWidth() - width);
        letter.layout(left, top, left + width, top + height);
    }

我做错了什么?提前谢谢。

UPD。 顺便说一句,我试图在onWindowFocusChanged中调用init(),它以正确的方式解决了IllegalArgumentException,top和left计数的问题,但是即使在letter.layout()

之后imageview仍然在左上角。

1 个答案:

答案 0 :(得分:1)

如果您下次发布LogCat / StackTrace会很有帮助。无论如何,问题出在以下几行:findViewById(R.id.e1_letter + i);您正在获取资源的引用ID并向其添加整数。这可能并不意味着什么。在null对象上设置某些内容将不起作用。 你可以更容易地遍历Rel​​ativeLayout的子节点,如下所示:

ViewGroup v = (ViewGroup) gameFieldView;
for(int i = 0; i < v.getChildCount(); ++i) {
    ImageView letter = (ImageView) v.getChildAt(i);
    generateRandomPosition(random, letter); 
}

这样您就不需要所有ImageView的ID