androidmoveandroid-relativelayoutsetx

Why does using Random() to setX() and setY() Certain devices make the view disappear?


Not sure if this has been answered. I did definitley search as hard as I could, because I feel like someone else would have had this issue. Basically I am using random along with setX and setY to move a view around randomly onClick. This works perfectly on my device and I went ahead and released the app. Although my brother uses a different device and said that as soon as he clicks the button, the view disappears from the screen.

My guess, obviously, is that the setX and setY just moved it off the screen. Anyone know how to make the view move only within the parent layout? I also need to keep my current random method in tact as it is integral to the game.

Here is my code for the button movement:

Random r = new Random();
int buttonHeight;
int buttonWidth;
buttonHeight = btnCount.getHeight();
buttonWidth = btnCount.getWidth();
int xLeft = r.nextInt(480 - buttonHeight);
int yUp = r.nextInt(800 - buttonHeight);
int xRight = r.nextInt(480 + buttonHeight);
int yDown = r.nextInt(800 + buttonHeight);

btnCount.setX(xLeft);
btnCount.setX(xRight);
btnCount.setX(yUp);
btnCount.setX(xDown);

Any ideas?

Backwards Compatibility

I do see a lot of how to questions about this, but if you want to help out 2 for 1 question here, any ideas on how to do the same method above for pre-API 11? If not that's cool I can just look up the other questions and methods after this gets fixed.


Solution

  • I found that finding the width and height on the current layout, no matter the device, and then dividing those values by 3, then taking the value divided by 3 and creating an int variable which is then used along with buttonHeight and buttonWidth works great on all devices to keep the button within screen. I understand this is probably not an ideal fix, but it is a quick one. I am still open to other suggestions.

    Thanks!