android - How to know when one moving view (overlaps) is on the top of the over -
(not sure title. please make right)
hi. i'm trying create small game, player can move objects inside ralativelayout
. want check whether moving object inside framelayout
or outside of it. example want change text of object when inside framelayout
.
so create objects inside for
loop way:
random random = new random(); (int = 0; < 3; i++) { //any number, not 3 textview textview = new textview(getactivity()); textview.setx(random.nextint(size.x - 200)); textview.sety(random.nextint(size.y - 200)); //scattered on screen textview.settext(i + ""); textview.setbackgroundcolor(getresources().getcolor(r.color.colorprimary)); textview.settextsize(50); relativelayout.layoutparams lp = new relativelayout.layoutparams( relativelayout.layoutparams.wrap_content, relativelayout.layoutparams.wrap_content); textview.setlayoutparams(lp); textview.setontouchlistener(touchlistener); framefor.addview(textview); }
there framelayout objects should be:
relativelayout.layoutparams framelp = new relativelayout.layoutparams(300, 300); framelp.addrule(relativelayout.center_in_parent, relativelayout.true); frameforletters.setlayoutparams(framelp);
as can see, added ontouchlistener
make objects movable:
view.ontouchlistener touchlistener = new view.ontouchlistener() { float dx, dy; @override public boolean ontouch(view view, motionevent event) { switch (event.getaction()) { case motionevent.action_down: dx = view.getx() - event.getrawx(); dy = view.gety() - event.getrawy(); break; case motionevent.action_move: view.animate() .x(event.getrawx() + dx) .y(event.getrawy() + dy) .setduration(0) .start(); break; default: return false; } return true; } };
in pic can see one , two inside framelayout
, 0 outside.
i know can done huge amount of geometry , calculation size of each object , framelayout itself. maybe there way of doing this? maybe there library or framework can make task easier?
i'm not aware of libraries or frameworks, can use these 2 methods determine if objects overlapping (the rect.intersects
method of calculations):
private rect getscreenbounds(view view) { int[] location = new int[2]; view.getlocationonscreen(location); return new rect(location[0], location[1], location[0] + view.getwidth(), location[1] + view.getheight()); } private boolean doviewsintersect(view target, view item) { rect targetrect = getscreenbounds(target); rect itemrect = getscreenbounds(item); return targetrect.intersects(itemrect); }
if you're interested in knowing if object inside other, targetrect
becomes rect
containing intersection. hence, can following see if item entirely inside target bounds:
if(targetrect.intersects(itemrect)) { return targetrect.width() == item.getwidth() && targetrect.height() == item.getheight(); } else { return false; }
Comments
Post a Comment