【发布时间】: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