在android上动态创建视图和getWidth方法

时间:2011-02-12 11:02:59

标签: android dynamic view views relativelayout

我在布局和视图上遇到了getWidth方法的问题,所以我尝试将创建和放置视图放在父级中。在开始时,活动启动方法loadResources(),它从数据库获取所有favicons,为它们创建imageview,并在将它们分配给relativeLayout父尝试将它们放置在屏幕上之后在其他循环中。但屏幕上什么都没有?

以下是代码:

private void loadResources() {

    cursor = managedQuery(Browser.BOOKMARKS_URI, projection, selection,
    null, Browser.BookmarkColumns.VISITS + " DESC");

    if(cursor.moveToFirst()) {
        bookmarkCounter = 1;
        ByteArrayInputStream blobImage;

        do{
           bookmark = new ImageView(this);
           bookmark.setId(bookmarkCounter++);
           bookmark.setBackgroundColor(Color.WHITE);

           blobImage = new ByteArrayInputStream(
                   cursor.getBlob(cursor.getColumnIndex(BookmarkColumns.FAVICON)));

           bookmark.setImageDrawable(
                   Drawable.createFromStream(blobImage, "" + bookmark.getId()));

           params = new RelativeLayout.LayoutParams(
                   (int) (40 * scale), (int) (40 * scale));

           params.topMargin = (int) (scale * 20);
           params.leftMargin = (int) (scale * 20);
           relativeLayout.addView(bookmark, params);
        } while (cursor.moveToNext());

        int idOfViewToTheLeft = 1;

        for(int counter = 1; counter < bookmarkCounter; counter++) {

            bookmark = (ImageView) findViewById(counter);

            Log.v("WIDTH", "" + relativeLayout.getWidth());

            if(bookmarkCounter > 1) {
               if(relativeLayout.getWidth() > (bookmark.getLeft() + bookmark.getWidth())) {
                   params.addRule(RelativeLayout.RIGHT_OF, bookmark.getId() - 1);
               } else {
                   params.addRule(RelativeLayout.BELOW, idOfViewToTheLeft);
                   idOfViewToTheLeft = bookmark.getId();
               }
            }

            bookmark.setScaleType(ScaleType.CENTER_CROP);

            bookmark.setLayoutParams(params);
        }

        setContentView(R.layout.main);

     }
    }

}

2 个答案:

答案 0 :(得分:1)

我通过使用screenwidth手动计算数学并设置布局参数的边距来解决这个问题。

答案 1 :(得分:1)

如果我能正确理解你的问题,我猜这就是你需要看的...........使用你的观点的onSizeChange()........这里是一个EXTENDED代码段http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html