user31231234124 user31231234124 - 12 days ago 7
Android Question

Unable to create a growing view

Im using the following code to animate the view when it is drawn...

public class MyView extends View {

int iCurStep = 0;// current animation step

class Points {
float x, y;

Points(float _x, float _y) {
x = _x;
y = _y;
}
}

Points[] drawPaths = {new Points(-75, 0), new Points(20, 60), new Points(60, 20)};


public MyView(Context context) {
super(context);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.STROKE);

Path path = new Path();
PathMeasure pm = new PathMeasure(path, false);

if (iCurStep <= 20) {
pm.getPosTan(fSegmentLen * iCurStep, afP, null);
path.moveTo(drawPaths[0].x, drawPaths[0].y);
for (int i = 1; i < drawPaths.length; i++) {
path.lineTo(drawPaths[i].y, drawPaths[i].y);
}
canvas.drawPath(path, paint);
iCurStep++;
} else {
iCurStep = 0;
}
}
}


What Im expecting is that, it has to be a growing view...I mean the view has to grow as it is being drawn...But Im not able to produce to do so...How can I be able to sort this out?

Answer

Use a ObjectAnimator.

Create your view as normal, but then create an ObjectAnimator (docs: https://developer.android.com/reference/android/animation/ObjectAnimator.html). You'll do something like this in your fragment or activity (you can make it in XML as well). Essentially you create an ObjectAnimator for an object with a property string. The property string must have a camelCase setter. So if you wanted to call view.setScaleX() as the property you were going to modify, you'd need to set the property string to 'scaleX'. Here's a simple example.

View growMe = new View(args);
float startSize = 1.0f;
float endSize = 2.0f;
ObjectAnimator grower = ObjectAnimator.ofFloat(growMe, "scaleX", startSize, endSize);
int durationMs = 1000;
grower.setDuration (durationMs)
grower.start();

The one other thing you'll need to do is add an AnimationListener to your View that actually adjusts the size to be the correct as the end of the animation as (I believe--I might be wrong on this part), the view will re-size after the animation ends.

I hope that helps!