【问题标题】:How i can change postion of the button randomly(inside the screen) in android? [duplicate]我如何在android中随机更改按钮的位置(屏幕内)? [复制]
【发布时间】:2012-11-13 21:25:53
【问题描述】:

可能重复:
How i can change postion of the button randomly in android by clicking the button

这是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tuch_me);
    btn = (Button) findViewById(R.id.bttuch);
    timer = (TextView) findViewById(R.id.tvtimer);
    timeout = (TextView) findViewById(R.id.tvtimeout);
    level = (TextView) findViewById(R.id.tvlevel);
    tv =(TextView) findViewById(R.id.textView1);
    btn.setOnClickListener(this);
    buttonWidth = 1;
    buttonHight = 1;

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_tuch_me, menu);
    return true;
}



@SuppressLint({ "NewApi", "NewApi" })
@TargetApi(11)
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bttuch:

        Random r = new Random();

        int xx=getResources().getDisplayMetrics().widthPixels;
        int yy=getResources().getDisplayMetrics().heightPixels;

        int x = r.nextInt(xx);
        int y = r.nextInt(yy);

        buttonWidth = btn.getWidth();
        buttonHight = btn.getHeight();

        btn.setX(xx-buttonWidth);
        btn.setY(yy-buttonHight);

        break;
    }

}
}

当我点击按钮时,它会跳出屏幕!我什至将实际分辨率设为 xx 和 yy,但它仍然不起作用。如何限制它停留在屏幕内?

【问题讨论】:

  • 您好,Sangeen。恕我直言,您没有听取在您现在已经问过 4 次的这个问题的先前答案中给您的建议。阿尔伯特爱因斯坦将精神错乱定义为一遍又一遍地做同样的事情并期待不同的结果。我怀疑你不会再得到一个好结果。你能做的最好的事情是学习一些基本的 Java,然后做一些 Android 教程。您还应该学习使用调试器。我向你保证,在调试器中单步执行代码会在第二次突出问题。开关上的断点并单步执行。祝你好运。
  • 好的先生,我已经在学习基本的java和Android教程了!我知道如何使用调试器。
  • 为什么要问第四次...?

标签: android button onclick location onchange


【解决方案1】:

你正在使用这条线

    btn.setX(xx-buttonWidth);
    btn.setY(yy-buttonHight);

当我认为你想这样做时

    btn.setX(x-buttonWidth);
    btn.setY(y-buttonHight);

因为您的变量 xxyy 不是随机的,但是您将 xy 整数设置为根据 xxyy 的值创建的随机整数

按钮离开屏幕的原因是因为你总是把它放在角落里,给你的按钮 x 和 y 坐标,它们是屏幕的全长。

希望这是有道理的

【讨论】:

  • 当我使用 btn.setX(x-buttonWidth);和 btn.setY(y-buttonHight);是的,它可以工作,但是当我在点击后继续点击时,它再次出现在屏幕外!即使是随机的 x = 4 和随机的 y = 189 它也会出现在屏幕之外!你能帮我修一下吗
  • 尝试将 buttonHeight 和 buttonWidth 设置为按钮的高度和宽度(您在 XML 中设置的高度和宽度),而不是使用获取它的方法
  • 我也这样做了,但点击后再次出现在屏幕之外,当随机 x=316 和 y 788 时。
  • 尝试将按钮的大小设置为px 而不是dp - dp 是缩放像素,因此在大小方面无法与像素相比,但px 应该是跨度>
  • 有一段时间随机 x=307 和 y=732 不出屏
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多