2013-09-01 15 views
0

我有一個應用程序,您可以點擊一個按鈕並將其轉換爲屏幕上的另一個點。如何在屏幕範圍內動畫按鈕

以下是我用於翻譯的內容。

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

但是,按鈕可能會部分轉換出屏幕,有時也會轉換到其他小部件之上。有沒有辦法避免這種情況?

回答

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> 

在上述佈局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> 

我希望這個解釋清除你的疑惑。