【问题标题】:Setting random button position within limits Java/Android在 Java/Android 限制范围内设置随机按钮位置
【发布时间】:2015-08-28 01:22:06
【问题描述】:

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

所以这就是我想要完成的,上面是视图的样子,我试图将按钮的位置限制在红色方块内。

这是我目前尝试过的代码:

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

我意识到这很可能不是处理它的最佳方式,但我真的不希望图标越过顶部和底部的视图,或者出现在右侧的外部。

有什么帮助吗?使用安卓工作室。顶部的图片显示了我希望它能够出现的范围。

【问题讨论】:

    标签: java android random


    【解决方案1】:

    我想出了自己的解决方案!所以我所做的是在现有布局中添加了第二个视图,该视图与图片中红色方块的大小相匹配,然后使用以下代码:

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

    它抓取了二级布局的宽度和高度,并使用它来设置按钮可以出现的位置,从而将其保持在正确的框架内

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      相关资源
      最近更新 更多