java - Randomly Placing view in a fragment -
i new android development, , trying place view (imageview
specific) in random place inside of fragment, i'm having lot of trouble. i've spent ridiculous amount of time trying find out how this, still can't figure out.
so originally, had random position of view thing working in regular activity using method:
relativelayout.layoutparams params = (relativelayout.layoutparams) button.getlayoutparams(); displaymetrics metrics = new displaymetrics(); getwindowmanager().getdefaultdisplay().getmetrics(metrics); params.leftmargin = new random().nextint(metrics.widthpixels - button.getwidth()); params.topmargin = new random().nextint(metrics.heightpixels - 2 * button.getheight()); button.setlayoutparams(params);
but doesn't work in fragment
because can't button.getwidth()
. tried using viewtreeobserver method, didn't understand going on , couldn't work me.
could please explain how can randomly place view inside of fragment, without view going outside of boundaries of fragment?
p.s. if answers "you should more research," please understand have literally spent 10 hours trying figure out, , have exhausted ideas of how can this.
"i can't button.getwidth()" - view's width , height not available until after it's been inflated. if try call button.getwidth()
inside oncreate
or oncreateview
, it'll return 0
because view has not yet been inflated.
instead, try callung button.getwidth()
in onactivitycreated
or onviewcreated
, callback methods let know when view's go.
Comments
Post a Comment