要在你想要的,你將需要添加這個範圍得到的Math.random()值 - :
bttn1.animate().translationX((float) (randomFromInterval(100,800)));
bttn2.animate().translationY((float) (randomFromInterval(200,500)));
public int randomFromInterval(int from,int to)
{
return (int) Math.floor(Math.random()*(to-from+1)+from);
}
如果你在其他小部件的頂部讓你的按鈕,那麼你將有放置按鈕,在你的相對佈局結束,因爲它管理根據你寫的XML佈局例如部件意見z軸的可視性 - :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Button1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:text="Button2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_below="@+id/button2"
android:text="Button3" />
</RelativeLayout>
在上述佈局BUTTON3是從z上最頂尖的看法軸,如果你需要使button1成爲z軸最高的視圖,那麼你將重新排列你的代碼是這樣的 - :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:text="Button2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_below="@+id/button2"
android:text="Button3" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Button1" />
</RelativeLayout>
我希望這個解釋清除你的疑惑。