Search code examples
c#xamarin.androidandroid-animationandroid-linearlayout

Layout animation randomly not visible


I am applying an animation to a Linear Layout like so:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    SetContentView(Resource.Layout.activity_main);

    testBtn = FindViewById<Button>(Resource.Id.testBtn);
    testLayout = FindViewById<LinearLayout>(Resource.Id.testLayout);
    testText = FindViewById<TextView>(Resource.Id.testText);
    testLayout.Visibility = ViewStates.Gone;
    
    slideIn = AnimationUtils.LoadAnimation(this, Resource.Animation.slide_in_right);

    testBtn.Click += delegate 
    {
      counter++;
      testText.Text = "Hello World " + counter;
      testLayout.Visibility = ViewStates.Gone;
      testLayout.StartAnimation(slideIn);
      testLayout.Visibility = ViewStates.Visible;
    };
}

slide_in_right.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <translate android:fromXDelta="-100%p" android:toXDelta="0"
             android:interpolator="@android:anim/accelerate_decelerate_interpolator"
             android:duration="300"/>
</set>

What I am seeing is maybe 25% of the time when the app starts, the animation and layout will not be visible when the button is pressed. This also seems to fix itself after starting a new activity and returning to this one. It also seems to be device dependent as some devices never show this problem while others encounter it frequently even on identical devices.

I have also tried other variations of animating shown below but so far nothing has seemed to help the situation.

testLayout.Animation = AnimationUtils.LoadAnimation(this, Resource.Animation.slide_in_right);
testLayout.Visibility = ViewStates.Visible;
testLayout.Animation.StartNow();
testLayout.Animation = new TranslateAnimation(-width, toXDelta: 0f, fromYDelta: 0f, toYDelta: 0f)
{
  Duration = 200
};
testLayout.Visibility = ViewStates.Visible;
testLayout.Animation.StartNow();

Solution

  • The Gone of the Visibility make the view invisible, and it doesn't take any space for layout purposes.

    Remove it would be okay:

     //testLayout.Visibility = ViewStates.Gone;