lundi 2 novembre 2015

How to rotate an image in Android and stop it randomly on button pressed

im trying to make a simple wheel of fortune in my android application. This will be a rounded image with person names. The image will start rotating(arround its center) when the button below it is pressed. The rotation needs to be stopped after a random time, so its not always the same person name ofcourse. for now i just use an image with 1-2-3-4, se below.

Output example

Ive looked at nearly every topic regarding this, but cant figure it out how to make it random. At the moment it always stops at the same angle, for instance always at number 1.

The code i have sofar:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_who, container, false);


   final ImageView alberto = (ImageView)view.findViewById(R.id.alberto);
    Button spin =(Button)view.findViewById(R.id.spin);

    final RotateAnimation anim = new RotateAnimation(0f,generateRandomNumber(), Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f);
    anim.setFillAfter(true);
    anim.setDuration(1000);


    spin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            alberto.startAnimation(anim);
        }
    });

    return view;
}

public float generateRandomNumber() {

    Random rand = new Random();
    int randomNum = rand.nextInt((360 - 0) + 1);

    return (float)randomNum;
}

}

So basicaly i give the RotateAnimation a random number, so its not always the same where it stops rotating. But this is not working becaus like i said it always stops on nr 1 for example. i figured out that if i change the duration of the animation the output is not the same! Therefor i tryed put a random number in in the duration but thats not working aswell.btw i have checked other posts that say its random but its not.

In the ideal situation the animation starts fast and slows down and stops.

Thanx allot in advanced!!!




Aucun commentaire:

Enregistrer un commentaire