How can I draw an animated view in android?

前端 未结 2 524
逝去的感伤
逝去的感伤 2020-12-13 23:20

I created a custom view from scratch. Extended View and overrided onDraw(). When comes down in animating the view i generate a custom animation usi

2条回答
  •  温柔的废话
    2020-12-13 23:29

    "What is best" of course depends greatly on exactly what you are trying to do. You haven't said what you are trying to accomplish, so we can only guess at what may be best for you.

    Here are some simple things:

    • If you want to animate bitmap frames, use AnimationDrawable: http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html

    • If you want to animate the movement of views within your hierarchy, use the view animation framework: http://developer.android.com/guide/topics/graphics/view-animation.html

    • The new more general animation framework can do a lot more stuff an is often easier to use: http://developer.android.com/guide/topics/graphics/animation.html. This is natively available in Android 3.0+ but can also be used in Android API level 7 with the support v7 library.

    • If you want to write a custom widget that is an integrated part of its view hierarchy and manually does its own animation drawing, you can use a Handler to time the updates (usually you'll want 60fps or 20ms between each invalidate()) and then in your onDraw() method draw your view's state based on SystemClock.uptimeMillis() as a delta from when the animation started.

    Here's a simple repeated invalidate using Handler:

    long mAnimStartTime;
    
    Handler mHandler = new Handler();
    Runnable mTick = new Runnable() {
        public void run() {
            invalidate();
            mHandler.postDelayed(this, 20); // 20ms == 60fps
        }
    }
    
    void startAnimation() {
        mAnimStartTime = SystemClock.uptimeMillis();
        mHandler.removeCallbacks(mTick);
        mHandler.post(mTick);
    }
    
    void stopAnimation() {
        mHandler.removeCallbacks(mTick);
    }
    

提交回复
热议问题