TransitionDrawable在自定义视图的onDraw中无法正常工作

时间:2015-06-04 14:23:12

标签: android android-custom-view android-drawable

我试图在自定义视图的onTouchEvent()内启动TransitionDrawable startTransition()方法。它仅显示xml文件中的第一个图像。然而,它适用于ImageView的{​​{1}}方法。将这两者结合起来是可能的还是在自定义视图中显示类似转换的其他替代方法。

transition.xml:

setDrawable()

初​​始化器:

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_icon_lock"/> // only this image is shown
    <item android:drawable="@drawable/ic_icon_unlock"/>
</transition>

onDraw()自定义视图:

mLockTransitionalDrawable = (TransitionDrawable)
            ResourcesCompat.getDrawable(mResources, R.drawable.transition, mContext.getTheme());

在包含drawable的矩形(mLockRect)内发生Action down时触发:

mLockTransitionalDrawable.setBounds(mLockRect);
    mLockTransitionalDrawable.draw(canvas);

由于时间限制,我正在寻找一个简单的解决方案。

1 个答案:

答案 0 :(得分:0)

感谢 pskink 的评论,我得到了它的工作。这是一些相关的代码。

创建Drawable.Callback对象或实现它:

mLockTransitionCallback = new Drawable.Callback() {
        @Override
        public void invalidateDrawable(Drawable who) {
            Log.e("invalidate called", "yes");
            invalidate(mLockRect);// don't call invalidate() it will invalidate the whole canvas I am only invalidating the region that I want to redraw

        }

        @Override
        public void scheduleDrawable(Drawable who, Runnable what, long when) {
            new Handler().postAtTime(what, who, when);// this will start the animation

        }

        @Override
        public void unscheduleDrawable(Drawable who, Runnable what) {
            Log.e("unschedule called","yes");
        }
    };

设置回调:

mLockTransitionalDrawable.setCallback(mLockTransitionCallback);