下面,我已经得到了Java和XML代码,基本上我想点击一个固定的按钮,并在屏幕上的第二个按钮跳跃在任意点将按钮的位置设置为屏幕上的随机点? - Android电子
XML解释: 所以,我有一个有两个按钮的相对布局......其中一个是固定在屏幕的底部......我想随机设置另一个的位置。
屏幕打开,点击固定按钮...另一个按钮的位置应随机更改。
说我再次点击固定按钮,然后agin,另一个按钮应该随机跳转。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Rrand" >
<Button
android:id="@+id/rbb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Button" />
<Button
android:id="@+id/bss"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:onClick="aa"
android:text="Button" />
</RelativeLayout>
JAVA解释 在这里,我已经得到了固定按钮的OnClick功能。
►b=这是应该跳来跳去
首先的按钮,我们得到的屏幕尺寸,然后使用的LayoutParams,利用随机函数设置按钮的位置。用于X
public void Clicky(View v) {
b = (Button) findViewById(R.id.rbb1);
///Getting the Screen dimensions for API 1+
LayoutParams params = (LayoutParams) b.getLayoutParams();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
///Setting the buttons paramaters, again for API 1+
params.leftMargin = b.getWidth()
+ new Random().nextInt(metrics.widthPixels - b.getWidth());
params.topMargin = b.getHeight()
+ new Random().nextInt(metrics.heightPixels - b.getHeight());
b.setLayoutParams(params);
}
随机函数坐标:
b.getWidth()+新的随机()nextInt(metrics.widthPixels - b.getWidth());。
最小值= b.getWidth()。
因此,在理论上,按钮应该永远不会出现在屏幕上。
在为nextInt的参数,我用[屏幕宽度 - 按钮宽度] ...所以,从理论上讲,它不应该走出去,从对方太屏幕...
问题 但它确实如此。大约一半时间,按钮甚至不会出现在屏幕上......问题必须出现在随机函数中(我认为是这样)......我只是希望它出现在屏幕上的随机点上。
我认为这个问题很简单的逻辑,因为我有我需要的所有功能..
这不起作用 ►Setting上的按钮和相对Layour的余量。 ►从随机函数中删除所有按钮尺寸参数。
也就是说,使用:
新的随机()nextInt(metrics.widthPixels)
所以,我怎么拿错?
都能跟得上! ...仍然不起作用(尽管它在屏幕上出现大约80%的时间......) – Zenis
如果您从XML文件中的RelativeLayout中移除填充项,那么该怎么办? – MalaKa
没关系!我得到它的工作....杂乱地与我在Random()中减去多少......以及我在外面添加了多少......:是的,事实证明,填充导致它在相撞时不可见:-) – Zenis