Skip to main content

How to animate Visibility/Invisibility view in Android?

 This post is related to show animation on any view in android.

 1) Simple Android Animation on View GONE/VISIBLE

If you just want a better transition view on GONE / VISIBLE rather than the default Android show/hide, I came across  some simple trick to make a simple animation using TranslateAnimation class.

*Note: For a better transitioning, you can use animationlistener , and setVisibility onAnimationStart() or onAnimationEnd().

// View to be animate (I use ImageView as example here)
ImageView imageView = (ImageView)findViewById(R.id.imageview);
Below are the methods to set view from VISIBLE to GONE

// To animate view slide out from left to right
public void slideToRight(View view){
TranslateAnimation animate = new TranslateAnimation(0,view.getWidth(),0,0);
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}
// To animate view slide out from right to left
public void slideToLeft(View view){
TranslateAnimation animate = new TranslateAnimation(0,-view.getWidth(),0,0);
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}
// To animate view slide out from top to bottom
public void slideToBottom(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,view.getHeight());
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}
// To animate view slide out from bottom to top
public void slideToTop(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,-view.getHeight());
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}



 2) In below code "rlSearchByLocationSub" is RelaiveLayout.

if (location) {
                    imgBtnLocation.setBackgroundResource(R.drawable.arrow_down);
                    rlSearchByNameSub.setVisibility(View.GONE);
                    rlSearchByLocationSub.setVisibility(View.VISIBLE);

                    // Animation
                    AnimationSet set = new AnimationSet(true);
                    Animation animation = new AlphaAnimation(0.0f, 1.0f);
                    animation.setDuration(150);
                    set.addAnimation(animation);
                    animation = new TranslateAnimation(
                            Animation.RELATIVE_TO_SELF, 0.0f,
                            Animation.RELATIVE_TO_SELF, 0.0f,
                            Animation.RELATIVE_TO_SELF, -1.0f,
                            Animation.RELATIVE_TO_SELF, 0.0f);
                    animation.setDuration(500);
                    set.addAnimation(animation);
                    LayoutAnimationController controller = new LayoutAnimationController(
                            set, 0.5f);
                    rlSearchByLocationSub.setLayoutAnimation(controller);


                    location = false;
                } else {
                    imgBtnLocation.setBackgroundResource(R.drawable.arrow_right);

                    // Animation
                    AlphaAnimation fade_out = new AlphaAnimation(1.0f, 0.0f);
                    fade_out.setDuration(500);
                    fade_out.setAnimationListener(new AnimationListener() {
                        public void onAnimationStart(Animation arg0) {
                        }

                        public void onAnimationRepeat(Animation arg0) {
                        }

                        public void onAnimationEnd(Animation arg0) {
                            rlSearchByLocationSub.setVisibility(View.GONE);
                        }
                    });
                    rlSearchByLocationSub.startAnimation(fade_out);

                    location = true;
               }

3) To show the button call this
AlphaAnimation fade_in = new AlphaAnimation(0.0f, 1.0f);
fade_in.setDuration(500);
fade_in.setAnimationListener(new AnimationListener()
{
    public void onAnimationStart(Animation arg0)
    {
    }
    public void onAnimationRepeat(Animation arg0)
    {
    }

    public void onAnimationEnd(Animation arg0)
    {
        myButton.setVisibility(View.VISIBLE);
    }
});
myButton.startAnimation(fade_in); 
Then to hide the button:
AlphaAnimation fade_out = new AlphaAnimation(1.0f, 0.0f);
fade_out.setDuration(upcoming_animation_time);
fade_out.setAnimationListener(new AnimationListener()
{
    public void onAnimationStart(Animation arg0)
    {
    }
    public void onAnimationRepeat(Animation arg0)
    {
    }

    public void onAnimationEnd(Animation arg0)
    {
        myButton.setVisibility(View.GONE);
    }
});
myButton.startAnimation(fade_out);
 
4)If I want to make an Animation for when a View gets it's visibility set 
  to GONE.
 
  public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.q2634073);
        findViewById(R.id.item1).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        view.startAnimation(new MyScaler(1.0f, 1.0f, 1.0f, 0.0f,  
                                                500, view, true));
    }

    public class MyScaler extends ScaleAnimation {

        private View mView;

        private LayoutParams mLayoutParams;

        private int mMarginBottomFromY, mMarginBottomToY;

        private boolean mVanishAfter = false;

        public MyScaler(float fromX, float toX, float fromY, float toY, 
             int duration, View view,boolean vanishAfter) {
            super(fromX, toX, fromY, toY);
            setDuration(duration);
            mView = view;
            mVanishAfter = vanishAfter;
            mLayoutParams = (LayoutParams) view.getLayoutParams();
            int height = mView.getHeight();
            mMarginBottomFromY = (int) (height * fromY) 
                              + mLayoutParams.bottomMargin - height;
            mMarginBottomToY = (int) (0 - ((height * toY)  
                            + mLayoutParams.bottomMargin)) - height;
        }

        @Override
        protected void applyTransformation(float interpolatedTime, 
                                            Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            if (interpolatedTime < 1.0f) {
                int newMarginBottom = mMarginBottomFromY
                        + (int) ((mMarginBottomToY - mMarginBottomFromY)  
                        * interpolatedTime);
                mLayoutParams.setMargins(mLayoutParams.leftMargin, 
                 mLayoutParams.topMargin,mLayoutParams.rightMargin, 
                                                     newMarginBottom);
                mView.getParent().requestLayout();
            } else if (mVanishAfter) {
                mView.setVisibility(View.GONE);
            }
        }

    }

}

Comments

Popular posts from this blog

Android: Check whether activity is in stack or not.

Solution There's possibility to check current tasks and their stack using ActivityManager . So, to determine if an activity is the last one: request android.permission.GET_TASKS permissions in the manifest. Use the following code: ActivityManager mngr = (ActivityManager) getSystemService( ACTIVITY_SERVICE );  List<ActivityManager.RunningTaskInfo> taskList = mngr.getRunningTasks(10); if(taskList.get(0).numActivities == 1 && taskList.get(0).topActivity.getClassName().equals(this.getClass().getName())) {             Log.i(TAG, "This is last activity in the stack");  }

Error: Retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

My project is going on easily but suddenly what I found below bugs when developing an app. I know it's minor bug but it may be useful to anyone. Here is the error: Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'. Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'. Solution: This happens because after updates your android studio uses API 23 by default. 1) First check that your compile SDK version must match the support library's major version. If you are using version 23 of the support library, you need to compile against version 23 of the Android SDK. Alternatively you can continue compiling against version 22 of the Android SDK by switching to the latest support library v22.   2) Go to your project structure -> Properties -> and change Build tool version to...

Fragment: App loads with white screen for 3 secs before showing proper UI

Issue: 1) When my application start then white/black screen appears, and then main UI is display.  2) Before my fragment load in activity black/white screen appears for 3/4 seconds and then fragment load. Solution: To fix this nasty problem, update the /res/values/styles.xml to include <item name="android:windowDisablePreview">true</item> or <item name="android:windowBackground">@android:color/black</item> for example : <!-- Application theme. -->  <style name="AppTheme" parent="AppBaseTheme">  <!-- All customizations that are NOT specific to a particular API-level can go here. -->  <item name="android:windowDisablePreview">true</item>  <!-- <item name="android:windowBackground">@android:color/black</item> -->  </style>