【问题标题】:TransitionDrawable not working inside custom view's onDrawTransitionDrawable 在自定义视图的 onDraw 中不起作用
【发布时间】:2015-06-04 14:23:11
【问题描述】:

我正在尝试在自定义视图的 onTouchEvent() 中启动 TransitionDrawable startTransition() 方法。它只显示 xml 文件中的第一个图像。然而,它适用于ImageViewsetDrawable() 方法。将这两者结合起来是可能的,或者是否有其他替代方法可以在自定义视图中显示类似的过渡。

transition.xml:

<?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>

初始化器:

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

onDraw() 自定义视图:

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

当 Action down 在包含可绘制对象的矩形(mLockRect)内发生时触发:

 mLockTransitionalDrawable.startTransition(1000); // does not change drawable layer invalidate() requestLayout() is not working either

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

【问题讨论】:

  • 你需要设置回调
  • Drawable.Callback 为什么我没有想到我会尝试并尝试回答我自己的问题谢谢@pskink
  • 我也认为TransitionDrawable 只适用于两个Drawables
  • @pskink 得到它的工作感谢您的精彩评论

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


【解决方案1】:

感谢 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);

【讨论】:

  • 好吧,您可以将您的视图用作 Drawable.Callback ...(视图实现 Drawable.Callback)在您的实现中 new Handler().postAtTime 可以多次调用,每次都创建新的处理程序
  • @pskink 你是对的,我将创建一个单独的处理程序,而不是按计划将其初始化可绘制
  • 正如我所说:你不需要实现整个回调接口,它已经在 View 类中完成,从你所说的你正在创建一个自定义 View,所以将它用作回调
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多