如何在屏幕范围内设置动画按钮

时间:2013-09-01 00:40:42

标签: android button

我有一个应用程序,您点击一个按钮,它将转换为屏幕上的另一个点。

这是我用于翻译的内容。

findViewById(R.id.clickButton).animate().translationX((float) (Math.random() * ( 100 - 400 )));
findViewById(R.id.clickButton).animate().translationY((float) (Math.random() * ( 100 - 400 )));

然而,按钮可以部分地从屏幕转换出来,有时也可以在其他小部件的顶部转换。有没有办法避免这种情况?

1 个答案:

答案 0 :(得分:0)

要在您想要的范围内获取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>

在上面的布局中,如果你需要让button1成为z轴上最顶层的视图,那么button3是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>

我希望这个解释清除你的怀疑。