2016-11-03 15 views
-1

私はバグを殺すのと同じようなゲームを作りたいのですが、そのバグはランダムな順序で動きます。しかし、ユーザーが触れると、画像がかすれたバグに変わります。AndroidでImageButtonをランダムにアニメーション化するには

AndroidでImageButtonのランダムな動きをアニメーション化するにはどうすればよいですか?

+0

出力のショーのスクリーンショット –

+0

私を更新下の例で答える – earthw0rmjim

答えて

1

あなたはViewPropertyAnimatorを使用することができ、ここでは簡単な例です:

activity_main.xml

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <ImageButton 
     android:id="@+id/imageButton1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerInParent="true" 
     android:src="@android:drawable/ic_dialog_info"/> 
</RelativeLayout> 

MainActivity.java

public class MainActivity extends AppCompatActivity implements Animator 
    .AnimatorListener { 

    Random random = new Random(); 
    ImageButton imageButton; 
    int maxX; 
    int maxY; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     imageButton = (ImageButton) findViewById(R.id.imageButton1); 

     imageButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // stopping the animation and changing the image 
       imageButton.animate().cancel(); 
       imageButton.setImageResource(android.R.drawable.ic_delete); 
      } 
     }); 

     imageButton.post(new Runnable() { 
      @Override 
      public void run() { 
       maxX = imageButton.getRootView() 
        .getRight() - imageButton.getWidth(); 
       maxY = imageButton.getRootView() 
        .getBottom() - imageButton.getHeight(); 

       animateButton(); 
      } 
     }); 
    } 

    @Override 
    public void onAnimationEnd(Animator animation) { 
     animateButton(); 
    } 

    private void animateButton() { 
     imageButton.animate() 
      .x(random.nextInt(maxX)) 
      .y(random.nextInt(maxY)) 
      .setDuration(1000) 
      .setListener(this); 
    } 

    @Override 
    public void onAnimationStart(Animator animation) { 
    } 

    @Override 
    public void onAnimationCancel(Animator animation) { 
    } 

    @Override 
    public void onAnimationRepeat(Animator animation) { 
    } 
}