[embedyt] https://www.youtube.com/watch?v=bqgseI9pHwE[/embedyt]
Downloadsactivity_main.xmlMainActivity.java
Image files:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/floor" tools:context="com.codinginflow.spinthebottle.MainActivity"> <ImageView android:id="@+id/bottle" android:layout_width="300dp" android:layout_height="300dp" android:src="@drawable/bottle" android:layout_centerInParent="true" android:onClick="spinBottle"/> </RelativeLayout>
package com.codinginflow.spinthebottle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.ImageView; import java.util.Random; public class MainActivity extends AppCompatActivity { private ImageView bottle; private Random random = new Random(); private int lastDir; private boolean spinning; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bottle = findViewById(R.id.bottle); } public void spinBottle(View v) { if (!spinning) { int newDir = random.nextInt(1800); float pivotX = bottle.getWidth() / 2; float pivotY = bottle.getHeight() / 2; Animation rotate = new RotateAnimation(lastDir, newDir, pivotX, pivotY); rotate.setDuration(2500); rotate.setFillAfter(true); rotate.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { spinning = true; } @Override public void onAnimationEnd(Animation animation) { spinning = false; } @Override public void onAnimationRepeat(Animation animation) { } }); lastDir = newDir; bottle.startAnimation(rotate); } } }