Showing posts with label android-animation. Show all posts
Showing posts with label android-animation. Show all posts

Thursday, October 11, 2018

How to shrink a finishing activity to a rectangle

Leave a Comment

In my Android app, I have a floating Activity. It's started from outside my app using ActivityOptions.makeScaleUpAnimation to scale up from an "originating" rectangle. When my Activity finishes, I'd like it to do the reverse of that animation: i.e. it shrinks back to that rectangle as it fades out.

I know I can get the rectangle with getIntent().getSourceBounds(), and I'd hoped to be able to use overridePendingTransition() when finishing to achieve this effect, but overridePendingTransition() can only accept a fixed XML resource: there doesn't seem to be a way to make that animation depend on the source bounds. Is there something else I can use to achieve this effect?

My app is for API 11+, but as it's a cosmetic effect only, I'd be satisfied with a solution that depends on a later version.

2 Answers

Answers 1

I don think there is a way to scale down the activity window other than the overridePendingTransition call. However this code may help:

Scale up

ActivityOptions opts = ActivityOptions.makeCustomAnimation(getActivity(), R.anim.scale_up, 0); startActivity(new Intent(this, SecondActivity.class),opts.toBundle());

Here is the scale_up animation file:

<set  xmlns:android="http://schemas.android.com/apk/res/android">     <scale     android:fromXScale="0"     android:toXScale="1.0"     android:fromYScale="0"     android:toYScale="1.0"     android:pivotX="50%p"     android:pivotY="50%p"     android:duration="500"/> </set> 

Scale down

Call this code from the exiting activity:

finish();  overridePendingTransition(0, R.anim.scale_down); 

Here is the scale_down animation file:

<set xmlns:android="http://schemas.android.com/apk/res/android">    <scale     android:fromXScale="1.0"     android:toXScale="0"     android:fromYScale="1.0"     android:toYScale="0"     android:pivotX="50%p"     android:pivotY="50%p"     android:duration="250"/> </set> 

You can vary the X and Y scale to get the desired rectangle. Hope this helps.

Answers 2

Based on my last comment, here is the solution which i have tried and it works. You may have to modify to suit your requirements.

Implement a Activity with Transparent background and with no title inside the manifest:

       <activity         android:name="com.example.backgroundsensor.AnimatedActivity"         android:theme="@android:style/Theme.Translucent.NoTitleBar"         android:label="Animated activity" />  

and let it set the content view with a layout as :

  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/container"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@android:color/transparent"    tools:ignore="MergeRootFrame" >      <View          android:id="@+id/visibleAreaView"         android:layout_width="300dp"         android:layout_height="300dp"         android:layout_gravity="center"         android:background="@android:color/holo_green_dark" />   </FrameLayout> 

The visibleAreaView is the one you will see on the screen, since activity is transparent. You can set the bounds of the view in OnCreate of the activity().

  @Override   protected void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.animated_activity);        // set the bounds of the animateView   } 

Also, Override the finish method something like this:

boolean animateFirst=true; @Override public void finish() {      if(animateFirst)      {          animateFirst = false;          loadAnim();       }else      {          super.finish();      } }   public void loadAnim() {      View v = findViewById(R.id.animateView);     float x= v.getX() + v.getRight()/2;     float y = v.getY();     anim = new ScaleAnimation(1.0f, 0.0f,1.0f, 0.0f, x, y);     anim.setDuration(300);     anim.setAnimationListener(new AnimationListener() {          @Override         public void onAnimationStart(Animation animation) {             // TODO Auto-generated method stub          }          @Override         public void onAnimationRepeat(Animation animation) {             // TODO Auto-generated method stub          }          @Override         public void onAnimationEnd(Animation animation) {             findViewById(R.id.animateView).setVisibility(View.GONE);             AnimatedActivity.this.finish();         }     });     v.startAnimation(anim);  } 
Read More

Monday, October 1, 2018

How to achieve Buttery Smooth ViewPager Shake animation

Leave a Comment

I am investigating Android ViewPager animation in my current project.

I would like to give my users an affordance in relation to my ViewPager.

The effect I am looking for it to "shake" the ViewPager from left to right to partially show the neighbouring pages to the selected page.

When the user selects the first page (F), I would "Shake" between F and F + 1.

When the user selects the last page (L), I would "Shake" between L and L - 1.

Otherwise, when the user selects any other page (X), I would "Shake" between X - 1, X and X + 1.

I have tried the following approaches which have all given unsatisfactory results.

Fake drag using screen density to calculate shake distance and valueAnimator and ObjectAnimator.  Animating ViewPager.PageTransformer. 

I am unable to get a satisfactory "Shake" effect.

I would like to achieve a Spring Dampening style of animation.

The FakeDrag was closest, although the effect was not reliable, it seemed to never work correctly the first time I started the animation.

Even the FakeDrag would not give the desired smooth shake between page swipes.

I would like to employ the physics-based animations on my view pager but couldn't see how.

Is it possible to achieve my desired animation?

UPDATE

I have developed this code which gives the desired effect, however its JANKY!

 @Override     protected void onResume() {         super.onResume();          final Handler handler = new Handler();         handler.postDelayed(() -> animateViewPager(ANIMATION_OFFSET, ANIMATION_DURATION), ANIMATION_DELAY);     }     /**      * @param offset      * @param duration      */     private void animateViewPager(final int offset, final int duration) {         if (animator.isRunning()) {             return;         }          animator.removeAllUpdateListeners();         animator.removeAllListeners();          animator.setIntValues(0, -offset);         animator.setDuration(duration);         animator.setRepeatCount(getRepeatCount());         animator.setRepeatMode(ValueAnimator.RESTART);         animator.addUpdateListener(constructUpdateListener());          animator.addListener(constructAnimatorListener());         animator.start();      }      /**      *      * @return      */     private Animator.AnimatorListener constructAnimatorListener() {         return new AnimatorListenerAdapter() {              @Override             public void onAnimationStart(final Animator animation) {                 animFactor = 1;             }              @Override             public void onAnimationEnd(final Animator animation) {                 viewPager.endFakeDrag();                 if (xAnimation == null) {                     xAnimation = createSpringAnimation(viewPager, SpringAnimation.X, 0, SpringForce.STIFFNESS_LOW, SpringForce.DAMPING_RATIO_HIGH_BOUNCY);                 } else {                     xAnimation.cancel();                 }                  viewPager.animate().x(viewPager.getWidth() * 0.1f).setDuration(0).start();                 xAnimation.start();             }              @Override             public void onAnimationRepeat(final Animator animation) {                 animFactor = -1;             }         };     }      /**      * @return      */     private int getRepeatCount() {         if (isOnlyPage()) {             return 0;         }          if (isFirstListItem()) {             return REPEAT_ONCE;         }          if (isLastListItem()) {             return REPEAT_ONCE;         }          return REPEAT_TWICE;     }      @SuppressWarnings("StatementWithEmptyBody")     private ValueAnimator.AnimatorUpdateListener constructUpdateListener() {         return animation -> {             final Integer value = animFactor * (Integer) animation.getAnimatedValue();             if (viewPager.isFakeDragging()) {             } else {                 viewPager.beginFakeDrag();             }             viewPager.fakeDragBy(value);         };     }      /**      * @param view      * @param property      * @param finalPosition      * @param stiffness      * @param dampingRatio      * @return      */     private SpringAnimation createSpringAnimation(final View view, final DynamicAnimation.ViewProperty property, final float finalPosition, final float stiffness, final float dampingRatio) {         final SpringAnimation animation = new SpringAnimation(view, property);         final SpringForce springForce = new SpringForce(finalPosition);         springForce.setStiffness(stiffness);         springForce.setDampingRatio(dampingRatio);         animation.setSpring(springForce);         return animation;     } 

0 Answers

Read More

Friday, August 10, 2018

android.graphics draw a line from one View pointing to another View

Leave a Comment

I know android.graphics is old, but i am having trouble doing a simple stuff.

I want to draw a line animation where one View points an arrow/line into another View

First Button-------------------------------->Second Button

I have tried creating a custom View class and overriding the onDraw(Canvas c) method and then using the drawLine(startX, startY, stopX, stopY, paint) method from the Canvas Object. But i don't know which coordinates to get in order to point one View to the other View

I don't want to create a static View in the XML layout with a slim height because the View can be added dynamically by the user, which i think drawing the line dynamically is the best way.

Please help me out. Thank you!

2 Answers

Answers 1

Use Path and Pathmeasure for Drawing Animated Line. I have Made and test it.

Make Custom View and pass view coordinates points array to it,

public class AnimatedLine extends View {     private final Paint mPaint;     public Canvas mCanvas;     AnimationListener animationListener;      Path path;     private static long animSpeedInMs = 2000;     private static final long animMsBetweenStrokes = 100;     private long animLastUpdate;     private boolean animRunning = true;     private int animCurrentCountour;     private float animCurrentPos;     private Path animPath;     private PathMeasure animPathMeasure;      float pathLength;       float distance = 0;     float[] pos;     float[] tan;     Matrix matrix;     Bitmap bm;       public AnimatedLine(Context context) {         this(context, null);         mCanvas = new Canvas();     }      public AnimatedLine(Context context, AttributeSet attrs) {         super(context, attrs);         mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);         mPaint.setStyle(Paint.Style.STROKE);         mPaint.setStrokeWidth(15);         mPaint.setStrokeCap(Paint.Cap.ROUND);         mPaint.setStrokeJoin(Paint.Join.ROUND);         mPaint.setColor(context.getResources().getColor(R.color.materialcolorpicker__red));           if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {             setLayerType(LAYER_TYPE_SOFTWARE, mPaint);         }         bm = BitmapFactory.decodeResource(getResources(), R.drawable.hand1);         bm = Bitmap.createScaledBitmap(bm, 20,20, false);         distance = 0;         pos = new float[2];         tan = new float[2];          matrix = new Matrix();     }      @Override     protected void onDraw(Canvas canvas) {         super.onDraw(canvas);          mCanvas = canvas;          if (path != null) {              if (animRunning) {                 drawAnimation(mCanvas);             } else {                 drawStatic(mCanvas);             }          }      }       /**      * draw Path With Animation      *      * @param time in milliseconds      */     public void drawWithAnimation(ArrayList<PointF> points, long time,AnimationListener animationListener) {         animRunning = true;         animPathMeasure = null;         animSpeedInMs = time;         setPath(points);         setAnimationListener(animationListener);         invalidate();     }      public void setPath(ArrayList<PointF> points) {         if (points.size() < 2) {             throw new IllegalStateException("Pass atleast two points.");         }         path = new Path();         path.moveTo(points.get(0).x, points.get(0).y);         path.lineTo(points.get(1).x, points.get(1).y);     }      private void drawAnimation(Canvas canvas) {         if (animPathMeasure == null) {             // Start of animation. Set it up.             animationListener.onAnimationStarted();             animPathMeasure = new PathMeasure(path, false);             animPathMeasure.nextContour();             animPath = new Path();             animLastUpdate = System.currentTimeMillis();             animCurrentCountour = 0;             animCurrentPos = 0.0f;              pathLength = animPathMeasure.getLength();           } else {             // Get time since last frame             long now = System.currentTimeMillis();             long timeSinceLast = now - animLastUpdate;              if (animCurrentPos == 0.0f) {                 timeSinceLast -= animMsBetweenStrokes;             }              if (timeSinceLast > 0) {                 // Get next segment of path                 float newPos = (float) (timeSinceLast) / (animSpeedInMs / pathLength) + animCurrentPos;                 boolean moveTo = (animCurrentPos == 0.0f);                 animPathMeasure.getSegment(animCurrentPos, newPos, animPath, moveTo);                 animCurrentPos = newPos;                 animLastUpdate = now;                   //start draw bitmap along path                 animPathMeasure.getPosTan(newPos, pos, tan);                 matrix.reset();                 matrix.postTranslate(pos[0], pos[1]);                 canvas.drawBitmap(bm, matrix, null);                 //end drawing bitmap                    //take current position                 animationListener.onAnimationUpdate(pos);                  // If this stroke is done, move on to next                 if (newPos > pathLength) {                     animCurrentPos = 0.0f;                     animCurrentCountour++;                     boolean more = animPathMeasure.nextContour();                     // Check if finished                     if (!more) {                         animationListener.onAnimationEnd();                         animRunning = false;                     }                 }             }              // Draw path             canvas.drawPath(animPath, mPaint);          }          invalidate();     }      private void drawStatic(Canvas canvas) {         canvas.drawPath(path, mPaint);         canvas.drawBitmap(bm, matrix, null);     }       public void setAnimationListener(AnimationListener animationListener) {         this.animationListener = animationListener;     }        public interface AnimationListener {         void onAnimationStarted();          void onAnimationEnd();          void onAnimationUpdate(float[] pos);     } } 

Answers 2

For drawing lines between views better if all of it lays on same parent layout. For the conditions of the question (Second Button is exactly to the right of First Button) you can use custom layout like that:

public class ArrowLayout extends RelativeLayout {      public static final String PROPERTY_X = "PROPERTY_X";     public static final String PROPERTY_Y = "PROPERTY_Y";      private final static double ARROW_ANGLE = Math.PI / 6;     private final static double ARROW_SIZE = 50;      private Paint mPaint;      private boolean mDrawArrow = false;     private Point mPointFrom = new Point();   // current (during animation) arrow start point     private Point mPointTo = new Point();     // current (during animation)  arrow end point      public ArrowLayout(Context context) {         super(context);         init();     }      public ArrowLayout(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }      public ArrowLayout(Context context, AttributeSet attrs, int defStyleAttr) {         super(context, attrs, defStyleAttr);         init();     }      public ArrowLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {         super(context, attrs, defStyleAttr, defStyleRes);         init();     }      private void init() {         setWillNotDraw(false);         mPaint = new Paint();         mPaint.setStyle(Paint.Style.STROKE);         mPaint.setAntiAlias(true);         mPaint.setColor(Color.BLUE);         mPaint.setStrokeWidth(5);     }      @Override     public void dispatchDraw(Canvas canvas) {         super.dispatchDraw(canvas);         canvas.save();         if (mDrawArrow) {             drawArrowLines(mPointFrom, mPointTo, canvas);         }         canvas.restore();     }      private Point calcPointFrom(Rect fromViewBounds, Rect toViewBounds) {         Point pointFrom = new Point();          pointFrom.x = fromViewBounds.right;         pointFrom.y = fromViewBounds.top + (fromViewBounds.bottom - fromViewBounds.top) / 2;          return pointFrom;     }       private Point calcPointTo(Rect fromViewBounds, Rect toViewBounds) {         Point pointTo = new Point();          pointTo.x = toViewBounds.left;         pointTo.y = toViewBounds.top + (toViewBounds.bottom - toViewBounds.top) / 2;          return pointTo;     }       private void drawArrowLines(Point pointFrom, Point pointTo, Canvas canvas) {         canvas.drawLine(pointFrom.x, pointFrom.y, pointTo.x, pointTo.y, mPaint);          double angle = Math.atan2(pointTo.y - pointFrom.y, pointTo.x - pointFrom.x);          int arrowX, arrowY;          arrowX = (int) (pointTo.x - ARROW_SIZE * Math.cos(angle + ARROW_ANGLE));         arrowY = (int) (pointTo.y - ARROW_SIZE * Math.sin(angle + ARROW_ANGLE));         canvas.drawLine(pointTo.x, pointTo.y, arrowX, arrowY, mPaint);          arrowX = (int) (pointTo.x - ARROW_SIZE * Math.cos(angle - ARROW_ANGLE));         arrowY = (int) (pointTo.y - ARROW_SIZE * Math.sin(angle - ARROW_ANGLE));         canvas.drawLine(pointTo.x, pointTo.y, arrowX, arrowY, mPaint);     }      public void animateArrows(int duration) {         mDrawArrow = true;          View fromView = getChildAt(0);         View toView = getChildAt(1);          // find from and to views bounds         Rect fromViewBounds = new Rect();         fromView.getDrawingRect(fromViewBounds);         offsetDescendantRectToMyCoords(fromView, fromViewBounds);          Rect toViewBounds = new Rect();         toView.getDrawingRect(toViewBounds);         offsetDescendantRectToMyCoords(toView, toViewBounds);          // calculate arrow sbegin and end points         Point pointFrom = calcPointFrom(fromViewBounds, toViewBounds);         Point pointTo = calcPointTo(fromViewBounds, toViewBounds);          ValueAnimator arrowAnimator = createArrowAnimator(pointFrom, pointTo, duration);         arrowAnimator.start();     }      private ValueAnimator createArrowAnimator(Point pointFrom, Point pointTo, int duration) {          final double angle = Math.atan2(pointTo.y - pointFrom.y, pointTo.x - pointFrom.x);          mPointFrom.x = pointFrom.x;         mPointFrom.y = pointFrom.y;          int firstX = (int) (pointFrom.x + ARROW_SIZE * Math.cos(angle));         int firstY = (int) (pointFrom.y + ARROW_SIZE * Math.sin(angle));          PropertyValuesHolder propertyX = PropertyValuesHolder.ofInt(PROPERTY_X, firstX, pointTo.x);         PropertyValuesHolder propertyY = PropertyValuesHolder.ofInt(PROPERTY_Y, firstY, pointTo.y);          ValueAnimator animator = new ValueAnimator();         animator.setValues(propertyX, propertyY);         animator.setDuration(duration);         // set other interpolator (if needed) here:         animator.setInterpolator(new AccelerateDecelerateInterpolator());          animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {             @Override             public void onAnimationUpdate(ValueAnimator valueAnimator) {                 mPointTo.x = (int) valueAnimator.getAnimatedValue(PROPERTY_X);                 mPointTo.y = (int) valueAnimator.getAnimatedValue(PROPERTY_Y);                  invalidate();             }         });          return animator;     } } 

with .xml layout like:

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"                 android:id="@+id/layout_main"                 android:layout_width="match_parent"                 android:layout_height="wrap_content">      <{YOUR_PACKAGE_NAME}.ArrowLayout             android:id="@+id/arrow_layout"             android:layout_width="match_parent"             android:layout_height="match_parent">          <Button             android:id="@+id/first_button"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_alignParentLeft="true"             android:text="First Button"/>          <Button             android:id="@+id/second_button"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_alignParentRight="true"             android:text="Second Button"/>      </{YOUR_PACKAGE_NAME}.ArrowLayout>  </RelativeLayout> 

and MainActivity.java like:

public class MainActivity extends AppCompatActivity {      private ArrowLayout mArrowLayout;     private Button mFirstButton;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          mArrowLayout = (ArrowLayout) findViewById(R.id.arrow_layout);          mFirstButton = (Button) findViewById(R.id.first_button);         mFirstButton.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 mArrowLayout.animateArrows(1000);             }         });     } } 

you got something like that (on First Button click):

[Arrow to View animated

For other cases ( Second Button is exactly to the left (or above, or below) or more complex above-right/below-left etc. of First Button) you should modify part for calculating arrow begin and end points:

private Point calcPointFrom(Rect fromViewBounds, Rect toViewBounds) {     Point pointFrom = new Point();      //                                Second Button above     //                                ----------+----------     //                               |                     |     //  Second Button tho the left   +     First Button    + Second Button tho the right     //                               |                     |     //                                ----------+----------     //                                  Second Button below     //     //   + - is arrow start point position      if (toViewBounds to the right of fromViewBounds){         pointFrom.x = fromViewBounds.right;         pointFrom.y = fromViewBounds.top + (fromViewBounds.bottom - fromViewBounds.top) / 2;     } else if (toViewBounds to the left of fromViewBounds) {         pointFrom.x = fromViewBounds.left;         pointFrom.y = fromViewBounds.top + (fromViewBounds.bottom - fromViewBounds.top) / 2;     } else if () {         ...     }      return pointFrom; } 
Read More

Wednesday, July 4, 2018

How to draw several lines slowly in constant velocity on canvas by Android?

Leave a Comment

I need capture the mark to draw a figure on canvas in Android, and the effect just like the follow gif:

enter image description here

Well, as far, I can draw a side with constant velocity by ValueAnimator. However, I just only can draw one side at one time, because I can't save the last side when drawing the next side. So, is there a good way to solve the problem?

Code for draw a line slowly by ValueAnimator:

GraphicsView.java

public class GraphicsView extends View {     private int stepX, stepY = 0;     private int startX, startY, stopX, stopY = 0;     private Paint paint = null;      public GraphicsView(Context context) {         super(context);          // Paint         paint = new Paint();         paint.setAntiAlias(true);         paint.setColor(Color.RED);         paint.setStyle(Paint.Style.STROKE);          startX = 40;         startY = 397;         stopX  = 1040;          stopY  = 397;          Init();     }      public void Init(){         ValueAnimator animatorX = ValueAnimator.ofFloat(startX, stopX);         ValueAnimator animatorY = ValueAnimator.ofFloat(startY, stopY);          animatorX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {             @Override             public void onAnimationUpdate(ValueAnimator valueAnimator) {                 stepX = Math.round((Float)valueAnimator.getAnimatedValue()); invalidate();             }         });         animatorY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {             @Override             public void onAnimationUpdate(ValueAnimator valueAnimator) {                 stepY = Math.round((Float)valueAnimator.getAnimatedValue()); invalidate();             }         });          AnimatorSet set = new AnimatorSet();         LinearInterpolator l = new LinearInterpolator();         set.setInterpolator(l);         set.setDuration(3000);         set.playTogether(animatorX, animatorY);         set.start();     }      @Override     protected void onDraw(Canvas canvas) {         super.onDraw(canvas);         canvas.drawLine(startX, startY, stepX, stepY, paint);     } } 

MainActivity.java

public class MainActivity extends AppCompatActivity {        private Display display         = null;       private GraphicsView view       = null;       private ConstraintLayout layout = null;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          display = getWindowManager().getDefaultDisplay();         layout = (ConstraintLayout)findViewById(R.id.main_layout);          view = new GraphicsView(this);         view.setMinimumWidth(display.getWidth());         view.setMinimumHeight(display.getHeight());            layout.addView(view);     } } 

1 Answers

Answers 1

you can use the ObjectAnimator class to callback to one of your class methods every time you'd like to draw a bit more of the path.

import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathEffect; import android.graphics.PathMeasure; import android.util.AttributeSet; import android.view.View; import android.util.Log;  public class PathView extends View {     Path path;     Paint paint;     float length;      public PathView(Context context)     {         super(context);     }      public PathView(Context context, AttributeSet attrs)     {         super(context, attrs);     }      public PathView(Context context, AttributeSet attrs, int defStyleAttr)     {         super(context, attrs, defStyleAttr);     }      public void init()     {         paint = new Paint();         paint.setColor(Color.BLUE);         paint.setStrokeWidth(10);         paint.setStyle(Paint.Style.STROKE);          path = new Path();         path.moveTo(50, 50);         path.lineTo(50, 500);         path.lineTo(200, 500);         path.lineTo(200, 300);         path.lineTo(350, 300);          // Measure the path         PathMeasure measure = new PathMeasure(path, false);         length = measure.getLength();          float[] intervals = new float[]{length, length};          ObjectAnimator animator = ObjectAnimator.ofFloat(PathView.this, "phase", 1.0f, 0.0f);         animator.setDuration(3000);         animator.start();     }      //is called by animtor object     public void setPhase(float phase)     {         Log.d("pathview","setPhase called with:" + String.valueOf(phase));         paint.setPathEffect(createPathEffect(length, phase, 0.0f));         invalidate();//will calll onDraw     }      private static PathEffect createPathEffect(float pathLength, float phase, float offset)     {         return new DashPathEffect(new float[] { pathLength, pathLength },             Math.max(phase * pathLength, offset));     }      @Override     public void onDraw(Canvas c)     {         super.onDraw(c);         c.drawPath(path, paint);     } } 

Then, just call init() to begin the animation, like this (or if you'd like it to start as soon as the view is inflated, put the init() call inside the constructors):

PathView path_view = (PathView) root_view.findViewById(R.id.path); path_view.init(); 

Also see this question here, and

Using Value Animator Example

Reference 1

Reference 2

Reference 3

Read More

Monday, July 2, 2018

Apply animation sequentially to multiple views

Leave a Comment

I have an activity with 3 views (buttonViews) in a vertical linear layout. I am generating (inflating) these views dynamically. I want to apply an animation such that, on activity start, the first buttons slide in -> 100 ms delay -> second button slide in -> 100 ms delay -> Third button slide in.

Attempt

I tried implementing it in this way:

private void setMainButtons() {     ArrayList<String> dashboardTitles = DashboardUtils.getDashboardTitles();     ArrayList<Integer> dashboardIcons = DashboardUtils.getDashboardIcons();      final ViewGroup root = findViewById(R.id.button_container);      for (int i = 0; i < (dashboardTitles.size() < dashboardIcons.size() ? dashboardTitles.size() : dashboardIcons.size()); i++){         final View buttonView = DashboardButtonInflater.getDashboardButton(root, dashboardTitles.get(i), dashboardIcons.get(i), this);         if (buttonView == null) continue;         buttonView.setOnClickListener(this);         root.addView(buttonView);         animateBottomToTop(buttonView, (long) (i*50)); // Calling method to animate buttonView     } }  //The function that adds animation to buttonView, with a delay. private void animateBottomToTop(final View buttonView,long delay) {     AnimationSet animationSet = new AnimationSet(false);     animationSet.addAnimation(bottomToTop);     animationSet.addAnimation(fadeIn);     animationSet.setStartOffset(delay);     buttonView.setAnimation(animationSet); } 

Result:

The above method waits for the total delay of all the views and at the end, aminates all the views together. I can guess the culprit here is the thread. The dealy is actually stopping the UI thread from doing any animation. I could be wrong though.

I also tried running the animation code inside

new Thread(new Runnable(){...}).run() 

but that didn't work either.

Expectations:

Can somebody help me achieve the one-by-one animation on buttonView? Thank you.

4 Answers

Answers 1

Animations are statefull objects, you should not use the same instance multiple times simultaneously. In your case the bottomToTop and fadeIn animations are shared between the animation sets. When the set starts (initialize() is called) it will set the start offset of its children.

For example the method could look like :

//The function that adds animation to buttonView, with a delay. private void animateBottomToTop(final View buttonView,long delay) {     AnimationSet animationSet = new AnimationSet(false);     // create new instances of the animations each time     animationSet.addAnimation(createBottomToTop());     animationSet.addAnimation(createFadeIn());     animationSet.setStartOffset(delay);     buttonView.setAnimation(animationSet); } 

Answers 2

The problem might be easily solved with Transitions API. Having declared a root layout with this xml:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   android:id="@+id/content_frame"   android:layout_width="match_parent"   android:layout_height="match_parent"   android:orientation="vertical"/> 

Then inside activity:

class MainActivity : AppCompatActivity() {      lateinit var content: LinearLayout     private var counter = 0      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          content = findViewById(R.id.content_frame)         // wait this view to be laid out and only then start adding and animating views         content.post { addNextChild() }     }      private fun addNextChild() {         // terminal condition         if (counter >= 3) return         ++counter          val button = createButton()         val slide = Slide()         slide.duration = 500         slide.startDelay = 100         slide.addListener(object : TransitionListenerAdapter() {             override fun onTransitionEnd(transition: Transition) {                 addNextChild()             }         })         TransitionManager.beginDelayedTransition(content, slide)         content.addView(button)     }      private fun createButton(): Button {         val button = Button(this)         button.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)         button.text = "button"         return button     }  } 

This chunk of code will result in following output:

You can adjust animation and delay times respectively.


If you want following behavior:

Then you can use following code:

class MainActivity : AppCompatActivity() {      lateinit var content: LinearLayout      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          content = findViewById(R.id.content_frame)         content.post { addChildren() }     }      private fun addChildren() {         val button1 = createButton()         val button2 = createButton()         val button3 = createButton()          val slide1 = Slide()         slide1.duration = 500         slide1.addTarget(button1)          val slide2 = Slide()         slide2.duration = 500         slide2.startDelay = 150         slide2.addTarget(button2)          val slide3 = Slide()         slide3.duration = 500         slide3.startDelay = 300         slide3.addTarget(button3)          val set = TransitionSet()         set.addTransition(slide1)         set.addTransition(slide2)         set.addTransition(slide3)          TransitionManager.beginDelayedTransition(content, set)         content.addView(button1)         content.addView(button2)         content.addView(button3)     }      private fun createButton(): Button {         val button = Button(this)         button.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)         button.text = "button"         return button     } } 

Answers 3

Create method, which will accept Any number of Animation to invoke one after another. Just as example.

private void playOneAfterAnother(@NonNull Queue<Animation> anims) {      final Animation next = anims.poll();       /* You can set any other paramters,       like delay, for each next   Playing view, if any of course */       next.addListener(new AnimationListener() {             @Override             public void onAnimationEnd(Animator a) {                 if (!anim.isEmpty()) {                     playOneAfterAnother(anims);                 }             }             @Override             public void onAnimationStart(Animator a) {             }             @Override             public void onAnimationCancel(Animator a) {             }             @Override             public void onAnimationRepeat(Animator a) {             }         });      next.play(); } 

Or with delay for animations, it's easy too.

private void playOneAfterAnother(@NonNull Queue<Animation> anims,                    long offsetBetween, int nextIndex) {      final Animation next = anims.poll();       /* You can set any other paramters,       like delay, for each next   Playing view, if any of course */       next.setStartOffset(offsetBetween * nextIndex);      next.play();       if (!anim.isEmpty()) {          playOneAfterAnother(anims,                offsetBetween, nextIndex +1);      }  } 

Answers 4

Probably, what you need to use is AnimatorSet instead of AnimationSet. The AnimatorSet API allows you to choreograph animations in two ways: 1. PlaySequentially 2. PlayTogether using the apis:

AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playSequentially(anim1, anim2, anim3, ...); animatorSet.playTogether(anim1, anim2, anim3, ...); 

You can further add delays to your animation using

animatorSet.setStartDelay(); 

Visit the complete API docs here https://developer.android.com/reference/android/animation/AnimatorSet

Hope this helps!

Read More

Tuesday, August 22, 2017

Animate layout change of bottom sheet

Leave a Comment

In my application I use a bottom sheet (from the support library) which works great. Now I would like to animate a layout change while the sheet is dragged up. For this I have created a subclass of BottomSheetCallback (this is normaly an inner class of a Fragment so not all objects used in this calss are initialized here):

public class MyBehavior extends BottomSheetBehavior.BottomSheetCallback {      Transition transition;     float lastOffset = 0;     Scene scene;      public PlayerBehavior() {         TransitionInflater inflater = TransitionInflater.from(getContext());         transition = inflater.inflateTransition(R.transition.player);         //transition.setDuration(300);          scene = fullLayout;          transition.setInterpolator(new Interpolator() {             @Override             public float getInterpolation(float v) {                 return lastOffset;             }         });     }      @Override     public void onStateChanged(@NonNull View bottomSheet, int newState) {         if(newState == BottomSheetBehavior.STATE_DRAGGING) {             TransitionManager.go(scene, transition);         }     }      @Override     public void onSlide(View bottomSheet, final float slideOffset) {         scene = (slideOffset > lastOffset) ? smallLayout : fullLayout;         lastOffset = slideOffset;     } } 

As you can see I also created two Scene from different layout files and a custom Transition to animate between the scenes with the TransitionManager. My problem is that the Transition should be based on the slideOffset parameter (in range of 0-1) but the TransitionManager uses the Animation class in the background which is normally time based in Android.

I tried to create the custom Intapolator but this does not work properly. So how can I create a Transition which is based on an external variable and not on time?

0 Answers

Read More

Wednesday, August 9, 2017

Animate top and bottom dimensions of a view

Leave a Comment

I need to 2 two things with a view:

  1. Move top dimension to the very top of the window
  2. Move bottom dimension to the very bottom of the window.

In short, I need the view to cover the 100% of the parent view.

Translation animation didn't work because It moves the view but it doesn't increase the size

Scale animation works but it stretch the content of the view and I don't want that. I want to increase the visible area, not to stretch the content to fit the new dimensions.

What's the correct way to do this?

6 Answers

Answers 1

That can be easily achieved with Transitions API.

With Transitions API you do not take care of writing animations, you just tell what you want the end values be and Transitions API would take care of constructing animations.

Having this xml as content view (a view in the center of the screen):

<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/root"     android:layout_width="match_parent"     android:layout_height="match_parent">      <View         android:id="@+id/view"         android:layout_width="120dp"         android:layout_height="80dp"         android:layout_gravity="center"         android:background="@color/colorAccent" />  </FrameLayout> 

In activity:

override fun onCreate(savedInstanceState: Bundle?) {     super.onCreate(savedInstanceState)     setContentView(R.layout.item)      val root = findViewById(R.id.root) as ViewGroup     val view = findViewById(R.id.view)      view.setOnClickListener {          // After this line Transitions API would start counting the delta         // and will take care of creating animations for each view in `root`         TransitionManager.beginDelayedTransition(root)          // By default AutoTransition would be applied,         // but you can provide your transition with the second parameter          // val transition = AutoTransition()         // transition.duration = 2000         // TransitionManager.beginDelayedTransition(root, transition)          // We are changing size of the view to match parent         val params = view.layoutParams         params.height = ViewGroup.LayoutParams.MATCH_PARENT         params.width = ViewGroup.LayoutParams.MATCH_PARENT          view.requestLayout()     } } 

Here's the output:

Platform's Transitions API (android.transition.TransitionManager) is available from API 19, but support libraries backport the functionality upto API 14 (android.support.transition.TransitionManager).

Answers 2

You can try using ValueAnimator as shown in this answer: https://stackoverflow.com/a/32835417/3965050

Note: I wanted to write this as a comment, but I don't have the reputation. This should not be considered as a full answer.

Answers 3

I like to keep everything as simple as it can be.

so my suggestion would be using a android Animating Layout Changes

Here is a sample:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:animateLayoutChanges="true"     android:animationCache="true">      <TextView         android:id="@+id/textView"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="@string/app_name"         android:background="@color/colorPrimary"         android:layout_gravity="center" />  </LinearLayout> 

MainActivity.java

public class MainActivity extends AppCompatActivity {      TextView textView;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          textView = (TextView) findViewById(R.id.textView);     }      @Override     protected void onResume() {         super.onResume();          new Handler().postDelayed(new Runnable() {             @Override             public void run() {                  View view = getWindow().getDecorView();                  int height = getWindow().getDecorView().getHeight();                 int width = getWindow().getDecorView().getWidth();                 textView.setLayoutParams(new LinearLayout.LayoutParams(width, height));                  LayoutTransition layoutTransition = ((ViewGroup) textView.getParent()).getLayoutTransition();                 layoutTransition.enableTransitionType(LayoutTransition.CHANGING);             }         }, 2000);     } } 

Answers 4

animateLayoutChanges="true" in the parent xml 

+

.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 

does the trick most of the times and it won't stretch the existing child views

Answers 5

Using ConstraintLayout with ConstrainSet should match your need in the most efficient way.

public class MainActivity extends AppCompatActivity {     ConstraintSet mConstraintSet1 = new ConstraintSet(); // create a Constraint Set     ConstraintSet mConstraintSet2 = new ConstraintSet(); // create a Constraint Set     ConstraintLayout mConstraintLayout; // cache the ConstraintLayout     boolean mOld = true;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         Context context = this;         mConstraintSet2.clone(context, R.layout.state2); // get constraints from layout         setContentView(R.layout.state1);         mConstraintLayout = (ConstraintLayout) findViewById(R.id.activity_main);         mConstraintSet1.clone(mConstraintLayout); // get constraints from ConstraintSet     }      public void foo(View view) {         TransitionManager.beginDelayedTransition(mConstraintLayout);         if (mOld = !mOld) {             mConstraintSet1.applyTo(mConstraintLayout); // set new constraints         }  else {             mConstraintSet2.applyTo(mConstraintLayout); // set new constraints         }     } } 

Source https://developer.android.com/reference/android/support/constraint/ConstraintSet.html

All you need is to define a second layout.xml with your expanded constraints and apply the second ConstraintSet to your view or activity when necessary.

Answers 6

ValueAnimator anim = ValueAnimator.ofInt(viewToIncreaseHeight.getMeasuredHeight(), -100); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {     @Override     public void onAnimationUpdate(ValueAnimator valueAnimator) {         int val = (Integer) valueAnimator.getAnimatedValue();         ViewGroup.LayoutParams layoutParams = viewGroup.getLayoutParams();         layoutParams.height = val;         viewGroup.setLayoutParams(layoutParams);     } }); anim.setDuration(DURATION); anim.start();  
Read More

Wednesday, March 22, 2017

Android: animated custom views

Leave a Comment

EDIT: My contributions/Resources

On my end, I found Lottie, that plays Affter Effects animations. Unfortunately, we can't create those animations neither we own the software.

Apart from that, also found this blog where an amazing train animation is explained.


Note

I am aware Android provides transformations such as scale, alpha, rotate, translation etc.

Examples

There are 2 examples I would like to look at and compare.

1 - Custom View animations

For example, filling up a glass of water or drawing a path.

2 - Complex View animations

For instance, StackExchange App for Android, login screen animation (couldn't find a video on it, also, didn't check if behaves the same in iOS).

Question

For the first example, I can't think of any other way than playing GIFs, or manually changing images after little time periods.

I do not think this is the case, that's why I would like to ask, (1) do you know how it's done?

Regarding the second example, only one idea came to my mind, and that's setting a Path and moving the View accordingly by passing it somehow after animate(). (2) Is this possible?

Apart from the mentioned above, (3) do you know of other techniques to play animations? (Such as Scene transitions - mentioned in an answer-)

Please share! Thank you.

3 Answers

Answers 1

"Filling up a glass of water" animation is direct canditate of implementing via frame animation, i.e. changing pictures one after the other. Here you can see a nice blog post describing how to implement this kind of animation, which basically is the same as "filling up a glass of water" you mentioned:

enter image description here

The other animation look slightly difficult at first glance.

enter image description here

But after turning on "Show layout bounds" you can see there is no magic there. Basically this is just a translation animation, which translates a view from one position to another. In case of this animation the difficult part is to implement the algorithm of finding translation coordinates. After that animating is just a couple lines of code via scene transition animation.

// assuming at this step all the views are at the initial position at x0, y0 TransitionManager.beginDelayedTransition(rootLayout); // here set view coordinates to x1, y1 - the final position 

Transitions framework will do the rest for you. It will find the delta and perform animation for you. Here you will find a nice article by Lucas Rocha.

Answers 2

do you know of other techniques to play animations?

In Android you have basically 3 ways to implement animations:

  • Animate the View (Scale, alpha, rotate, etc) by just using view.startAnimation(...)
  • Animate the Drawable (Depending on the Drawable, this could be anything from animated vector drawables to frame animations)
  • Doing custom drawing and animation

Obviously just animating a view by framework methods is easier than creating some drawable animation, and creating some drawable (xml) is easier than doing custom drawing.

You mentioned lottie, which just came out a few days ago. We shall see how well it does, but it looks very promising. Under the hood lottie will parse the json and do some custom drawing using Canvas and Path (3rd bullet point above)
If you can get your hands on After Effects this is probably the "easiest" solution for complex animations (and cross platform!)

People also started sharing animations, you can find them here:
http://www.lottiefiles.com/


do you know how it's done?

The (1) video looks like they do some custom drawing.

  • Draw and fill a Path for the water, animate the top with some waves while it animates up, and sprinkle with some white spots.
  • Draw a the shape of the glass around it

This will involve creating a custom view and/or drawable and overriding onDraw(Canvas) Path.lineTo as well as some arc, cubic, or quad will do the trick...I'm neither a designer nor a vector specialist :)

I do not think this could easily be achieved by using animated vector drawables, but you might get it done by applying a path morph animation. (Also animated vector drawables are only supported on 21+ if I am not mistaken)

The (2) Video just animates a Path and wiggles a flag. This can be achieved by using AnimatedVectorDrawables (as e.g. this blog shows) and trimming the path beginnings/ends or again by doing custom drawing (and thus also supporting pre lolipop devices) by animating a Path, e.g. using PathMeasure.getSegment() to continuuously animate the path.

The (3) animation, as already pointed out by azizbekians answer is the first mentioned kind, just animating (moving and scaling) views.


Regarding the second example, only one idea came to my mind, and that's setting a Path and moving the View accordingly by passing it somehow after animate(). (2) Is this possible?

Moving views along a path is obviously possible, but then the view would move, and you would still need to find a way to draw the path following it, as explained above.

Answers 3

For Your Custom view , i suggest you identify the Properties that you want to Animate on .

Let's say a ClockView, You After setting paint,stroke and so on in OnDraw()

You might wanna have AsyncMethods/Runnables which updates the Properties continuously in background , resulting in Frame by frame animation , but it isn't Fraame Animation actually , because you are animating only the properties of view (turn left) and not he tentire frame

There are dozens of examples out there, With little googling you can DIY

Read More

Friday, June 24, 2016

How to animate ImageView from center-crop to fill the screen and vice versa (facebook style)?

Leave a Comment

Background

Facebook app has a nice transition animation between a small image on a post, and an enlarged mode of it that the user can also zoom to it.

As I see it, the animation not only enlarges and moves the imageView according to its previous location and size, but also reveals content instead of stretching the content of the imageView.

This can be seen using the next sketch i've made:

enter image description here

The question

How did they do it? did they really have 2 views animating to reveal the content?

How did they make it so fluid as if it's a single view?

the only tutorial i've seen (link here) of an image that is enlarged to full screen doesn't show well when the thumbnail is set to be center-crop.

Not only that, but it works even on low API of Android.

does anybody know of a library that has a similar ability?


EDIT: I've found a way and posted an answer, but it's based on changing the layoutParams , and i think it's not efficient and recommended.

I've tried using the normal animations and other animation tricks, but for now that's the only thing that worked for me.

If anyone know what to do in order to make it work in a better way, please write it down.

5 Answers

Answers 1

Ok, i've found a possible way to do it. i've made the layoutParams as variables that keep changing using the ObjectAnimator of the nineOldAndroids library. i think it's not the best way to achieve it since it causes a lot of onDraw and onLayout, but if the container has only a few views and doesn't change its size, maybe it's ok.

the assumption is that the imageView that i animate will take the exact needed size in the end, and that (currently) both the thumbnail and the animated imageView have the same container (but it should be easy to change it.

as i've tested, it is also possible to add zoom features by extending the TouchImageView class . you just set the scale type in the beginning to center-crop, and when the animation ends you set it back to matrix, and if you want, you can set the layoutParams to fill the entire container (and set the margin to 0,0).

i also wonder how come the AnimatorSet didn't work for me, so i will show here something that works, hoping someone could tell me what i should do.

here's the code:

MainActivity.java

public class MainActivity extends Activity {     private static final int IMAGE_RES_ID = R.drawable.test_image_res_id;     private static final int ANIM_DURATION = 5000;     private final Handler mHandler = new Handler();     private ImageView mThumbnailImageView;     private CustomImageView mFullImageView;     private Point mFitSizeBitmap;      @Override     protected void onCreate(final Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         mFullImageView = (CustomImageView) findViewById(R.id.fullImageView);         mThumbnailImageView = (ImageView) findViewById(R.id.thumbnailImageView);         mHandler.postDelayed(new Runnable() {              @Override             public void run() {                 prepareAndStartAnimation();             }          }, 2000);     }      private void prepareAndStartAnimation() {         final int thumbX = mThumbnailImageView.getLeft(), thumbY = mThumbnailImageView.getTop();         final int thumbWidth = mThumbnailImageView.getWidth(), thumbHeight = mThumbnailImageView.getHeight();         final View container = (View) mFullImageView.getParent();         final int containerWidth = container.getWidth(), containerHeight = container.getHeight();         final Options bitmapOptions = getBitmapOptions(getResources(), IMAGE_RES_ID);         mFitSizeBitmap = getFitSize(bitmapOptions.outWidth, bitmapOptions.outHeight, containerWidth, containerHeight);          mThumbnailImageView.setVisibility(View.GONE);         mFullImageView.setVisibility(View.VISIBLE);         mFullImageView.setContentWidth(thumbWidth);         mFullImageView.setContentHeight(thumbHeight);         mFullImageView.setContentX(thumbX);         mFullImageView.setContentY(thumbY);         runEnterAnimation(containerWidth, containerHeight);     }      private Point getFitSize(final int width, final int height, final int containerWidth, final int containerHeight) {         int resultHeight, resultWidth;         resultHeight = height * containerWidth / width;         if (resultHeight <= containerHeight) {             resultWidth = containerWidth;         } else {             resultWidth = width * containerHeight / height;             resultHeight = containerHeight;         }         return new Point(resultWidth, resultHeight);     }      public void runEnterAnimation(final int containerWidth, final int containerHeight) {         final ObjectAnimator widthAnim = ObjectAnimator.ofInt(mFullImageView, "contentWidth", mFitSizeBitmap.x)                 .setDuration(ANIM_DURATION);         final ObjectAnimator heightAnim = ObjectAnimator.ofInt(mFullImageView, "contentHeight", mFitSizeBitmap.y)                 .setDuration(ANIM_DURATION);         final ObjectAnimator xAnim = ObjectAnimator.ofInt(mFullImageView, "contentX",                 (containerWidth - mFitSizeBitmap.x) / 2).setDuration(ANIM_DURATION);         final ObjectAnimator yAnim = ObjectAnimator.ofInt(mFullImageView, "contentY",                 (containerHeight - mFitSizeBitmap.y) / 2).setDuration(ANIM_DURATION);         widthAnim.start();         heightAnim.start();         xAnim.start();         yAnim.start();         // TODO check why using AnimatorSet doesn't work here:         // final com.nineoldandroids.animation.AnimatorSet set = new AnimatorSet();         // set.playTogether(widthAnim, heightAnim, xAnim, yAnim);     }      public static BitmapFactory.Options getBitmapOptions(final Resources res, final int resId) {         final BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();         bitmapOptions.inJustDecodeBounds = true;         BitmapFactory.decodeResource(res, resId, bitmapOptions);         return bitmapOptions;     }  } 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity" >      <com.example.facebookstylepictureanimationtest.CustomImageView         android:id="@+id/fullImageView"         android:layout_width="0px"         android:layout_height="0px"         android:background="#33ff0000"         android:scaleType="centerCrop"         android:src="@drawable/test_image_res_id"         android:visibility="invisible" />      <ImageView         android:id="@+id/thumbnailImageView"         android:layout_width="100dp"         android:layout_height="100dp"         android:layout_alignParentBottom="true"         android:layout_alignParentRight="true"         android:scaleType="centerCrop"         android:src="@drawable/test_image_res_id" />  </RelativeLayout> 

CustomImageView.java

public class CustomImageView extends ImageView {     public CustomImageView(final Context context) {         super(context);     }      public CustomImageView(final Context context, final AttributeSet attrs) {         super(context, attrs);     }      public CustomImageView(final Context context, final AttributeSet attrs, final int defStyle) {         super(context, attrs, defStyle);     }      public void setContentHeight(final int contentHeight) {         final LayoutParams layoutParams = getLayoutParams();         layoutParams.height = contentHeight;         setLayoutParams(layoutParams);     }      public void setContentWidth(final int contentWidth) {         final LayoutParams layoutParams = getLayoutParams();         layoutParams.width = contentWidth;         setLayoutParams(layoutParams);     }      public int getContentHeight() {         return getLayoutParams().height;     }      public int getContentWidth() {         return getLayoutParams().width;     }      public int getContentX() {         return ((MarginLayoutParams) getLayoutParams()).leftMargin;     }      public void setContentX(final int contentX) {         final MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();         layoutParams.leftMargin = contentX;         setLayoutParams(layoutParams);     }      public int getContentY() {         return ((MarginLayoutParams) getLayoutParams()).topMargin;     }      public void setContentY(final int contentY) {         final MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();         layoutParams.topMargin = contentY;         setLayoutParams(layoutParams);     }  } 

Answers 2

Another solution, if you just want to make an animation of an image from small to large, you can try ActivityOptions.makeThumbnailScaleUpAnimation or makeScaleUpAnimationand see if they suit you.

http://developer.android.com/reference/android/app/ActivityOptions.html#makeThumbnailScaleUpAnimation(android.view.View, android.graphics.Bitmap, int, int)

Answers 3

I found a way to get a similar affect in a quick prototype. It might not be suitable for production use (I'm still investigating), but it is quick and easy.

  1. Use a fade transition on your activity/fragment transition (which starts with the ImageView in exactly the same position). The fragment version:

    final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();     fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);     ...etc     

    The activity version:

    Intent intent = new Intent(context, MyDetailActivity.class); startActivity(intent); getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); 

    This gives a smooth transition without a flicker.

  2. Adjust the layouts dynamically in the onStart() of the new fragment (you need to save member fields to the appropriate parts of your UI in onCreateView, and add some flags to ensure this code only gets called once).

    @Override     public void onStart() {         super.onStart();      // Remove the padding on any layouts that the image view is inside     mMainLayout.setPadding(0, 0, 0, 0);      // Get the screen size using a utility method, e.g.      //  http://stackoverflow.com/a/12082061/112705     // then work out your desired height, e.g. using the image aspect ratio.     int desiredHeight = (int) (screenWidth * imgAspectRatio);      // Resize the image to fill the whole screen width, removing      // any layout margins that it might have (you may need to remove      // padding too)     LinearLayout.LayoutParams layoutParams =             new LinearLayout.LayoutParams(screenWidth, desiredHeight);     layoutParams.setMargins(0, 0, 0, 0);      mImageView.setLayoutParams(layoutParams); }     

Answers 4

I think the easiest way is to animate the height of the ImageView (a regular imageview, not necessary a custom view) while keeping the scaleType to centerCrop until full height, which you can know in advance if you set the image height to wrap_content in your layout and then use a ViewTreeObserver to know when the layout has ended, so you can get the ImageView height and then set the new "collapsed" height. I have not tested it but this is how I would do it.

You can also have a look at this post, they do something similar http://nerds.airbnb.com/host-experience-android/

Answers 5

I'm not sure why everyone is talking about the framework. Using other peoples code can be great at times; but it sounds like what you are after is precise control over the look. By getting access to the graphics context you can have that. The task is pretty simple in any environment that has a graphics context. In android you can get it by overriding the onDraw method and using the Canvas Object. It has everything you need to draw an image at many different scales, positions and clippings. You can even use a matrix if your familiar with that type of thing.

Steps

  1. Make sure you have exact control of positioning, scale, and clip. This means disabling any layouts or auto-alignment that might be setup inside your objects container.

  2. Figure you out what your parameter t will be for linear interpolation and how you will want it to relate to time. How fast or slow, and will there be any easing. t should be dependent on time.

  3. After the thumbnails are cached, load the full scale image in the background. But don't show it yet.

  4. When the animation trigger fires, show the large image and drive your animation with your t parameter using interpolation between the initial properties' states to the final properties' states. Do this for all three properties, position, scale and clip. So for all properties do the following:

    Sinterpolated = Sinitial * (t-1)    +   Sfinal * t; // where //    t is between 0.0 and 1.0 //    and S is the states value //    for every part of scale, position, and clip // //    Sinitial is what you are going from //    Sfinal   is what you are going to //     //    t should change from 0.0->1.0 in //    over time anywhere from 12/sec or 60/sec. 

If all your properties are driven by the same parameter the animation will be smooth. As an added bonus, here is a tip for timing. As long as you can keep your t parameter between 0 and 1, easing in or out can be hacked with one line of code:

// After your t is all setup t = t * t;        // for easing in // or t = Math.sqrt(t); // for easing out 
Read More

Friday, April 29, 2016

Using a coordinatorlayout to collapse a full screen imageview and replace it with viewpager with headers

Leave a Comment

I started playing around with coordinatoralyout and I'm trying to achieve the behavior on the attached image, I want a background image to be on full screen size and upon a scroll I want some textviews to dissapear and some to stick as parts of a viewpager (rather then a toolbarlayout) any guidance on how can I achieve this?

enter image description here

3 Answers

Answers 1

As I am not sure if you want a particular or a general solution, I am going to give you my solution for your particular question. The key is to work with scrollFlags and collapseMode. If you really want to hide the tabs when the appBar is expanded, you can play with visibility.

<?xml version="1.0" encoding="utf-8"?>  <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent">  <android.support.design.widget.AppBarLayout     android:id="@+id/appBar"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">     <android.support.design.widget.CollapsingToolbarLayout         android:id="@+id/collapsing_toolbar"         android:layout_width="match_parent"         android:layout_height="wrap_content"         app:contentScrim="?attr/colorPrimary"         app:layout_scrollFlags="scroll|enterAlways|snap">          <RelativeLayout             android:layout_marginTop="?attr/actionBarSize"             android:layout_width="match_parent"             android:layout_height="wrap_content">              <ImageView                 android:id="@+id/image"                 android:layout_width="match_parent"                 android:layout_height="375dp"                 android:src="@drawable/ic_launcher"/>              <LinearLayout                 android:layout_marginBottom="30dp"                 android:layout_below="@+id/image"                 android:layout_width="match_parent"                 android:orientation="horizontal"                 android:layout_height="wrap_content">                  <TextView                     android:layout_marginLeft="30dp"                     android:layout_width="wrap_content"                     android:layout_height="wrap_content"                     android:textSize="20sp"                     android:text="textView1"/>                  <TextView                     android:layout_marginLeft="140dp"                     android:layout_width="wrap_content"                     android:layout_height="wrap_content"                     android:textSize="20sp"                     android:text="textView2"/>              </LinearLayout>          </RelativeLayout>           <android.support.v7.widget.Toolbar             android:id="@+id/mToolbar"             android:layout_width="match_parent"             android:layout_height="?attr/actionBarSize"             app:popupTheme="@style/ThemeOverlay.AppCompat.Light"             app:layout_collapseMode="pin"/>      </android.support.design.widget.CollapsingToolbarLayout>      <LinearLayout         android:layout_width="match_parent"         android:orientation="horizontal"         android:layout_height="wrap_content">          <TextView             android:layout_marginLeft="30dp"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:textSize="20sp"             android:text="textView3"/>          <TextView             android:layout_marginLeft="140dp"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:textSize="20sp"             android:text="textView4"/>      </LinearLayout>      <android.support.design.widget.TabLayout         android:id="@+id/tabLayout"         android:layout_width="match_parent"         android:layout_height="?attr/actionBarSize"         android:layout_gravity="bottom"         android:background="?attr/colorPrimary"         app:tabMode="scrollable"/> </android.support.design.widget.AppBarLayout>  <android.support.v4.view.ViewPager     android:id="@+id/tab_viewpager"     android:layout_width="match_parent"     android:layout_height="match_parent"     app:layout_behavior="@string/appbar_scrolling_view_behavior" /> 

Answers 2

You can use layout_behavior to handle the strings which you want to be disappear upon scroll. Customise your view behaviour using CoordinatorLayout.Behavior

ViewBehavior.java

public class ViewBehavior extends CoordinatorLayout.Behavior<RelativeLayout> {  private Context mContext;  public ViewBehavior(Context context, AttributeSet attrs) {     mContext = context; }  @Override public boolean layoutDependsOn(CoordinatorLayout parent, RelativeLayout child, View dependency) {     return dependency instanceof AppBarLayout; }  @Override public boolean onDependentViewChanged(CoordinatorLayout parent, RelativeLayout child, View dependency) {     child.measure(View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(parent.getHeight(), View.MeasureSpec.AT_MOST));     int maxScroll = ((AppBarLayout) dependency).getTotalScrollRange();     float percentage = Math.abs(dependency.getY()) / (float) maxScroll;     float childPosition = dependency.getHeight()             + dependency.getY()             - child.getMeasuredHeight()             - (getToolbarHeight() - child.getMeasuredHeight()) * percentage / 2;      CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams();     child.setLayoutParams(lp);      child.setY(childPosition);     return true; }  public int getToolbarHeight() {     int result = 0;     TypedValue tv = new TypedValue();     if (mContext.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {         result = TypedValue.complexToDimensionPixelSize(tv.data, mContext.getResources().getDisplayMetrics());     }     return result; } } 

In layout xml, set your custom view behaviour as a app:layout_behavior in the view you want to handle.

activity_main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/coordinator_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true">  <android.support.design.widget.AppBarLayout     android:id="@+id/app_bar_layout"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:fitsSystemWindows="true"     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">      <android.support.design.widget.CollapsingToolbarLayout         android:id="@+id/collapsing_toolbar"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:fitsSystemWindows="true"         app:contentScrim="?attr/colorPrimary"         app:layout_scrollFlags="scroll|exitUntilCollapsed">          <ImageView             android:id="@+id/image"             android:layout_width="match_parent"             android:layout_height="match_parent"             android:fitsSystemWindows="true"             app:layout_collapseMode="parallax" />      </android.support.design.widget.CollapsingToolbarLayout>  </android.support.design.widget.AppBarLayout>  <android.support.v4.widget.NestedScrollView     android:layout_width="match_parent"     android:layout_height="match_parent"     android:fillViewport="true"     app:layout_behavior="@string/appbar_scrolling_view_behavior">      <LinearLayout         android:id="@+id/llViewPager"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:orientation="vertical">          <com.astuetz.PagerSlidingTabStrip             android:id="@+id/tabs"             android:layout_width="match_parent"             android:layout_height="48dp"             android:textColor="@color/red"             app:pstsShouldExpand="true"             app:pstsTextAllCaps="true" />          <android.support.v4.view.ViewPager             android:id="@+id/viewpager"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:background="@android:color/white" />     </LinearLayout> </android.support.v4.widget.NestedScrollView>  <RelativeLayout     android:layout_width="match_parent"     android:layout_height="match_parent"     app:layout_behavior="com.stacktest.ViewBehavior">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_marginBottom="20dp"         android:layout_marginLeft="36dp"         android:layout_marginTop="20dp"         android:text="Text-1" />      <TextView         android:id="@+id/txt2"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentRight="true"         android:layout_marginBottom="20dp"         android:layout_marginRight="36dp"         android:layout_marginTop="20dp"         android:text="Text-2" />      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_below="@id/txt2"         android:layout_marginBottom="20dp"         android:layout_marginLeft="36dp"         android:paddingRight="20dp"         android:text="Text-3" />      <TextView         android:id="@+id/txt4"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentRight="true"         android:layout_below="@id/txt2"         android:layout_marginBottom="20dp"         android:layout_marginRight="36dp"         android:text="Text-4" /> </RelativeLayout> </android.support.design.widget.CoordinatorLayout> 

Finally, use the layout and create ViewPager and Tabs in your Activity class.

MainActivity.java

public class MainActivity extends AppCompatActivity {  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);      ((CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar)).setTitle(" ");      ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);     viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));      PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);     tabsStrip.setViewPager(viewPager); }  public class MyPagerAdapter extends FragmentPagerAdapter {     final int PAGE_COUNT = 2;     private String tabTitles[] = new String[] { "Tab1", "Tab2" };      public MyPagerAdapter(FragmentManager fm) {         super(fm);     }      @Override     public int getCount() {         return PAGE_COUNT;     }      @Override     public Fragment getItem(int position) {         return TestFragment.newInstance(position + 1);     }      @Override     public CharSequence getPageTitle(int position) {         return tabTitles[position];     } } } 

Add following extra dependency in build.gradle along with appcompat and support library.

  • com.android.support:design:23.2.1
  • com.astuetz:pagerslidingtabstrip:1.0.1 (for ViewPager tabs)

Answers 3

http://d-codepages.com/collapsing-toolbar-android-example/

this link should help you. You can play around with this sample project.

Read More

Wednesday, April 13, 2016

android explode transition doesn't explode GridView

Leave a Comment

I am trying to use explode exit transition on a grid view. However, the only thing that flies away radially is the floating button at the bottom of the screen. The GridView cells slide away as a single unit. How do I make these cells "explode"?

Here is my style.xml :

<resources>      <!-- Base application theme. -->     <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">         <!-- Customize your theme here. -->         <item name="colorPrimary">@color/colorPrimary</item>         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>         <item name="colorAccent">@color/colorAccent</item>         <item name="colorControlActivated">@color/colorAccent</item>         <item name="colorControlHighlight">@color/colorAccent</item>         <item name="windowActionBar">false</item>         <item name="windowNoTitle">true</item>         <!-- Animation items -->         <item name="android:windowActivityTransitions">true</item>         <item name="android:windowContentTransitions">true</item>         <item name="android:windowEnterTransition">@android:transition/fade</item>         <item name="android:windowExitTransition">@android:transition/explode</item>     </style>  </resources> 

Here is the onCreate of the GridView activity that I am trying to explode :

protected void onCreate(Bundle savedInstanceState) {         getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);         super.onCreate(savedInstanceState);         getWindow().setExitTransition(new Explode());         setContentView(R.layout.activity_main); 

Alternately, If you know of examples that contain GridView explode transitions please feel free to post them.

1 Answers

Answers 1

GridView works as one element, if you need every element of it to move in different directions - you need to configure animation for each element in dependence of it's position and launch all of them on exit before launching main exit animation.

Read More

Saturday, April 2, 2016

Animation through points array

Leave a Comment

I'm sure there is an easy way to do this but I'm stuck. Let's say I have a list of points :

Point[] list = {pointA, pointB, pointC, ...} 

I'd like to animate an ImageView through each point So I tried this :

id = 0; AnimatorListenerAdapter animEnd = new AnimatorListenerAdapter() {     @Override     public void onAnimationEnd(Animator animation) {         super.onAnimationEnd(animation);         id++;         if(id != list.length) {             iv.animate()                 .translationX(list[id].getX())                 .translationY(list[id].getY())                 .setDuration(200)                 .setListener(this);         }     } };  iv.animate()     .translationX(list[id].getX()).translationY(list[id].getY())     .setDuration(200).setListener(animEnd); 

It works but there 's a slight delay between each animation.

Any idea? Thanks !

1 Answers

Answers 1

You probably get the delays between your animation steps because you always start a fresh animation on each transition from step to step. To overcome this situation you have multiple options.

Keyframes

Here you can find a technique called Keyframe Animation, which is a very common animation technique and is probably exactly what you want.

A Keyframe object consists of a time/value pair that lets you define a specific state at a specific time of an animation. Each keyframe can also have its own interpolator to control the behavior of the animation in the interval between the previous keyframe's time and the time of this keyframe.

Keyframe kf0 = Keyframe.ofFloat(0f, 0f); Keyframe kf1 = Keyframe.ofFloat(.5f, 360f); Keyframe kf2 = Keyframe.ofFloat(1f, 0f); PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2); ObjectAnimator rotationAnim = ObjectAnimator.ofPropertyValuesHolder(target, pvhRotation) rotationAnim.setDuration(5000ms); 

In your case you could map the points in your list to a list of Keyframe instances and ...

Point[] list = {pointA, pointB, pointC, ...} List<Keyframe> kfs = new ArrayList<Keyframe>(); foreach (Point p : points) {   Keyframe kf = new Keyframe.ofFloat(p.x); // or what ever   kfs.add(kf); } 

... later pass these keyframes to some factory method to create some PropertyValuesHolder, like ofFloat that has the following signature:

public static PropertyValuesHolder ofFloat (     Property<?, Float> property,      float... values ) 

The second parameter is a variable argument list which also accepts arrays as inputs. Thus it should be possible to pass your kfs to the method as a second argument, somehow.

In your case i would craft the following methods, since you are developing for dalvik VM you cannot use java8 lambda expressions:

// maps points to X/Y float values List<Float> toArrayX(Point[] points) { ... } List<Float> toArrayY(Point[] points) { ... } // maps float values to Keyframes List<Keyframe> toKeyframes(List<Float> floats) { ... } void createAnimation(Point[] points) {   List<Keyframe> xs = toKeyframes(toArrayX(points));   PropertyValuesHolder phvX = PropertyValuesHolder     .ofKeyframe("translationX", xs);    List<Keyframe> ys = toKeyframes(toArrayY(points));   PropertyValuesHolder phvY = PropertyValuesHolder     .ofKeyframe("translationY", ys);    linkPropertyValuesHolder(phvX);   linkPropertyValuesHolder(phvY); } void linkPropertyValuesHolder(PropertyValuesHolder phv) {   // setup target   ObjectAnimator anim = ObjectAnimator     .ofPropertyValuesHolder(target, phv)   anim.setDuration(5000ms); } 

Interpolators

Alternatively you can specify the transitions given by the points through an Interpolator instance.

An interpolator defines the rate of change of an animation. This allows the basic animation effects (alpha, scale, translate, rotate) to be accelerated, decelerated, repeated, etc.

An interpolator maps a fractional float between 0.0 and 1.0 to another fractional float between 0.0 and 1.0. Like the following three; LinearInterpolator, AccelerateDecelerateInterpolator and BounceInterpolator:

Images from here

Path Interpolator

With PathInterpolators it is possible to draw arbritary interpolators using Path instances. The drawn path will be used to drive the animation. In your case you could create two paths, one for the x and another one for the y translation.

However, take care when constructing interpolators from paths, because

... the Path must conform to a function y = f(x).

The Path must not have gaps in the x direction and must not loop back on itself such that there can be two points sharing the same x coordinate. It is alright to have a disjoint line in the vertical direction:

So take a look at the following code snippet that is taken from here, creates a valid path and could be used as input for the PathInterpolator constructor.

Path path = new Path(); path.lineTo(0.25f, 0.25f); path.moveTo(0.25f, 0.5f); path.lineTo(1f, 1f); 

Custom Interpolator

When the given interpolators are not flexible enough, you can also just implement the Interpolator interface and create a new instance from it afterwards. The interface is very narrow and it only provides a single method called getInterpolation with the following signature.

public abstract float getInterpolation (float input)     

Code vs. XML

Another last option is to move all the animation configuration into XML instead of baking these details directly into the binary distribution of the code. However, each of the given options will require a different setup to be manageable through XML, if possible.

Hope this helps, but it is only pseudo code. I didn't test the code... so no warranties for correctness.

Read More

Tuesday, March 15, 2016

Custom Property animation not working on disabling animation

Leave a Comment

I am creating an android application where each fragment is bind to a custom left to right slide animation. That i achieved using Custom Property Animation(FractionLinearLayout.java class given below). My app has several Fragment, switching among these fragment is followed by a right to left slide animation. Everything is working perfect untill i disable animation from Developer Options for testing purpose.

Nothing appears when i disable animations. I can see logcats means app is working perfect just views are not being loaded, (May be) because of the custom properties FractionTranslationX and FractionTranslationY.

Has anyone gone through this problem? Thanks in advance.

FractionLinearLayout.java: custom class for animation

public class FractionLinearLayout extends LinearLayout {      DisplayMetrics matrics = getContext().getResources().getDisplayMetrics();      public FractionLinearLayout(Context context, AttributeSet attrs,                                 int defStyleAttr) {         super(context, attrs, defStyleAttr);         // TODO Auto-generated constructor stub     }      public FractionLinearLayout(Context context) {         super(context);         // TODO Auto-generated constructor stub      }      public FractionLinearLayout(Context context, AttributeSet attrs) {         super(context, attrs);         // TODO Auto-generated constructor stub     }      public float getFractionTranslationX() {          return getWidth() > 0 ? super.getTranslationX() / getWidth() : Float.MAX_VALUE;     }      public void setFractionTranslationX(float translationX) {          int width = getWidth();         super.setTranslationX(width > 0 ? width * translationX : Float.MAX_VALUE);     }      public float getFractionTranslationY() {          return getHeight() > 0 ? super.getTranslationX() / getHeight() : Float.MAX_VALUE;     }      public void setFractionTranslationY(float translationY) {         int height = getHeight();         super.setTranslationY(height > 0 ? height * translationY : Float.MAX_VALUE);     }      public float getAnimWidth() {          return getLayoutParams().width;     }      public void setAnimWidth(int animWidth) {          getLayoutParams().width = animWidth;         requestLayout();     } } 

layout file of fragment:

fragment_main_layout.xml

<?xml version="1.0" encoding="utf-8"?> <com.bbi.views.FractionLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:background="@drawable/esc_app_background"     android:orientation="vertical"> ........... ........... </com.bbi.views.FractionLinearLayout> 

Custom animation xml file:

alide_in_left.xml

<?xml version="1.0" encoding="utf-8"?> <set     xmlns:android="http://schemas.android.com/apk/res/android"     android:interpolator="@android:anim/decelerate_interpolator">     <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"         android:duration="@integer/animation_time"         android:propertyName="fractionTranslationX"         android:valueFrom="1"         android:valueTo="0"         android:valueType="floatType" />  </set> 

slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?> <set     xmlns:android="http://schemas.android.com/apk/res/android"     android:interpolator="@android:anim/accelerate_interpolator">     <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"         android:duration="@integer/animation_time"         android:propertyName="fractionTranslationX"         android:valueFrom="0"         android:valueTo="-1"         android:valueType="floatType" />  </set> 

Code to add fragment on Activity:

getFragmentManager().beginTransaction()                 .setCustomAnimations(R.anim.slide_in_left;, R.anim.slide_out_left)                 .replace(R.id.frameTopContainer, newsToolFragment)                 .commitAllowingStateLoss(); 

When i replace com.views.FractionLinearLayout to LinearLayout in fragment_main_layout.xml, everything works fine(not animation obvious as i have disabled animation and removed property custom animation).

1 Answers

Answers 1

Finally solved my issue by reading animation_scale flag and removing setCustomAnimations() method according to that.

Read More