Issue
I am learning mobile development using android studio and Java. I tried to implement a flip card animation to build a flip card memory like game (without a library) and without expanding to another activity. I am basically using a function to flip the image then replace it, but the image gets replaced then it rotates. Find the code i worked on below. The function will later support flipping back the images if the flipped 2 images do not match, or increase a score by 1 if they match.
public void flipCard(View view){
ImageView card = (ImageView) view;
card.animate().rotationYBy(180);
card.SetImageResource(R.drawable.ex1);
}
Solution
To replace the image after the completion of the flip animation you have to use the withEndAction(Runnable runnable) method of ViewPropertyAnimator
.
Example is like below:
public void flipCard(View view){
ImageView card = (ImageView) view;
card.setImageResource(0);
card.animate().rotationYBy(180).withEndAction(new Runnable(){
@Override
public void run() {
card.setImageResource(android.R.drawable.ic_dialog_alert);
}
});
}
To revert back the two images after a certain time you can change the rotationYBy to -180
and you can use the setStartDelay
method to start the animation after an amount of time in milliseconds.
Example is like below:
public void flipCardToInitialState(View view){
ImageView card = (ImageView) view;
card.animate().rotationYBy(-180).setStartDelay(1000).withEndAction(new Runnable(){
@Override
public void run() {
card.setImageResource(0);
}
});
}
And you can use it in case the two images do not match like below:
flipCardToInitialState(imageView1);
flipCardToInitialState(imageView2);
You can also use Handler().postDelayed
to flip the two images back after a certain time in milliseconds:
//flip the 2 images
flipCard(imageView1);
flipCard(imageView2);
//and if the don't match flip the back after a certain of time in milliseconds
if(theyDontMatch)
{
runOnUiThread(new Runnable() {
@Override
public void run() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
flipCardToInitialState(imageView1);
flipCardToInitialState(imageView2);
}
}, 2000); //flip them back after 2 seconds delay
}
});
}
Answered By - MariosP