Jordan Maurice
Jordan Maurice

Reputation: 71

Setting random button position within limits Java/Android

http://puu.sh/ilLDM/374202dbc6.png

So here is what I'm trying to accomplish, above is what the view looks like, I'm trying to limit the position of the button to the red square.

Here is the code I have tried so far:

ImageButton charButton = (ImageButton) findViewById(R.id.goodIcon);
charButton.setImageDrawable(x);
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
width = width - 100; //Wont go within 100 of the screen edge
height = height - 100; //Wont go within 100 of bottom edge
Random r1 = new Random();
int Button1H = r1.nextInt(height - 200) + 200;
if (Button1H<100) {Button1H = 100;}
if (Button1H >= displayMetrics.heightPixels-100){Button1H = displayMetrics.heightPixels-100;}
int Button1W = r1.nextInt(width - 50) +50;
if (Button1W >= displayMetrics.widthPixels-100){Button1W = displayMetrics.widthPixels - 300;}
charButton.setX(Button1W);
charButton.setY(Button1H);

I realize this is most likely not the best way of handling it, but I really don't want the icon going over the views at the top and bottom, or appearing on outside on the right hand side.

Any help? Using Android Studio. Picture at the top shows the range of where I want it to be able to appear.

Upvotes: 4

Views: 1293

Answers (1)

Jordan Maurice
Jordan Maurice

Reputation: 71

I came up with my own solution! So what I did was I added a second view to the existing layout that matched the size of the red square in the picture then used this code:

    ImageButton charButton = (ImageButton) findViewById(R.id.goodIcon);
    RelativeLayout gameLayout = (RelativeLayout) findViewById(R.id.gameLayout);
    int width  = gameLayout.getWidth();
    int height = gameLayout.getHeight();
    charButton.setImageDrawable(x);
    int x = width;
    int y = height;
    Random buttonPlace = new Random();
    int buttonY = buttonPlace.nextInt(y-100)+100;
    int buttonX = buttonPlace.nextInt(x-50)+50;
    charButton.setX(buttonX);
    charButton.setY(buttonY);

Which grabbed the width and height of the secondary layout and used that to set where the button could appear, thus keeping it within the correct frame

Upvotes: 1

Related Questions