Setting a random button position within the limits of Java / Android

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

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

Here is the code I've 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 understand that this is most likely not the best way to handle this, but I really do not want the icon to go over the views above and below or appear outside on the right side.

Any help? Using Android Studio. The image above shows the range where I want it to appear.

+4
source share
1 answer

! , , , :

    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);

, , ,

+1

All Articles