【问题标题】:Dynamic creation of views and getWidth methods on android在android上动态创建视图和getWidth方法
【发布时间】:2011-02-12 11:02:59
【问题描述】:

我在布局和视图上的 getWidth 方法有问题,所以我尝试在父视图中分离视图的创建和放置。在开始时,Activity 启动方法 loadResources(),该方法从数据库中获取所有 favicon,为它们创建图像视图,并在将它们分配给 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);

     }
    }

}

【问题讨论】:

  • 您将setcontentview 放在方法的最后,这只会将空的、未绑定的 layout.main 应用到屏幕。
  • 没错,我删除了它。现在我只得到 1 个图标,似乎我没有正确更新视图的位置。该怎么做?
  • 您无法在 onCreate() 中获取大小或位置,它们只有在布局视图后才会起作用。关键是你在 oncreate 中做布局工作:你应该创建自己的布局,从 RelativeLayout 派生,覆盖 onLayout() 并在那里完成工作。
  • 好的,谢谢,你能给我参考一下教程吗?

标签: android dynamic view views android-relativelayout


【解决方案1】:

我通过使用屏幕宽度手动计算数学并设置布局参数的边距解决了这个问题。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2015-07-24
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      相关资源
      最近更新 更多