Dynamic creation of views and getWidth methods on android
I had problems with getWidth methods on layouts and views so I tried separating creation and placing of views inside parent. At start, activity starts the method loadResources() which gets all favicons from database, creates imageviews for them and in other loop after assigning them to relativeLayout parent tries placing them on screen. But nothing is on screen??
Here's the code:
private void loadResources() {
cursor = managedQuery(Browser.BOOKMARKS_URI, projection, selection,
null, Browser.BookmarkColumns.VISITS + " DESC");
if(cursor.moveToFirst()) {
bookmarkCounter = 1;
ByteArrayInput开发者_高级运维Stream 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);
}
}
}
I solved this problem by working out the math manually with screenwidth and setting the margins of layout params.
if i can understand your question correctly, i guess this is what you need to look at........... use onSizeChange() of your view........ here is an EXTENDED code snippet http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html
精彩评论