glassraven glassraven - 20 days ago 6
Android Question

How to set element invisible with animation?

I have this toggle button that when it is on, calls an animation method that sets several elements visible. But when I turn it off, the elements remain visible, although the opposite instruction. How can I make them disapear with the same logic? Do I have to create another method? Thanks, here's the code:

drum.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
key1.setVisibility(View.VISIBLE);
key1.startAnimation(fadeInAnimation());

key2.setVisibility(View.VISIBLE);
key2.startAnimation(fadeInAnimation());

key3.setVisibility(View.VISIBLE);
key3.startAnimation(fadeInAnimation());


rocking.setLooping(true);
rocking.start();

Toast.makeText(getApplicationContext(), "Rock and Rolling!", Toast.LENGTH_SHORT).show();
} else {
rocking.setLooping(false);
key1.setVisibility(View.INVISIBLE);// These instrucions are ignored...
key2.setVisibility(View.INVISIBLE);
key3.setVisibility(View.INVISIBLE);

Toast.makeText(getApplicationContext(), "Can't keep up? Try the tamborine!", Toast.LENGTH_SHORT).show();

}
}
});


And the animation method:

private Animation fadeInAnimation() {
Animation animation = new AlphaAnimation(0f, 1.0f);
animation.setDuration(1000);
animation.setFillEnabled(true);
animation.setFillAfter(true);
return animation;
}

Answer

Change the fadeInAnimation and pass a boolean argument, if true do fade-In animation else fade-out animation. Code sample is given below. Usage fadeAnimation(true) for fadeIn animation and fadeAnimation(false) for fadeOut animation. Hope this helps.

private Animation fadeAnimation(boolean fadeIn) {

 Animation animation = null;
 if(fadeIn)
    animation = new AlphaAnimation(0f, 1.0f);
 else
    animation = new AlphaAnimation(1.0f, 0f);
 animation.setDuration(1000); 
 animation.setFillEnabled(true);
 animation.setFillAfter(true);
 return animation;

}
Comments