我需要替换带有图像的文本短语,然后将其附加到TextView.对于常规Drawables,这没有问题,但是当Drawable是一个AnimationDrawable时,我不知道在何时何地调用.start();.
@H_404_2@这是我将文本追加到TextView的方法:
所以当我的drawable尚未完全附加到窗口时,我想我会调用我的.start(),但是我/何时/应该如何调用它? @H_404_2@提前致谢!
textview.append(Html.fromHtml(textWithHtmlImgTags,imagegetter,null));@H_404_2@使用imagegetter替换textWithHtmlImgTags中的图像标记:
new ImageGetter() { @Override public Drawable getDrawable(String source) { if(source.endsWith("_ani")) { Log.i("cmv","This is an animated drawable."); AnimationDrawable dra = (AnimationDrawable)res.getDrawable(sRes.get(source)); dra.setBounds(0,dra.getIntrinsicWidth(),dra.getIntrinsicHeight()); dra.start(); // This doesn't work.. return dra; } Drawable dr = res.getDrawable(sRes.get(source)); dr.setBounds(0,dr.getIntrinsicWidth(),dr.getIntrinsicHeight()); return dr; } };@H_404_2@添加了我的AnimationDrawables,但它们没有动画(它们被卡在第1帧上). @H_404_2@在文档中它说:
@H_404_2@It’s important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity,because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately,without requiring interaction,then you might want to call it from the onWindowFocusChanged() method in your Activity,which will get called when Android brings your window into focus.@H_404_2@由于图像是动态添加的,我认为它与onCreate()没有任何关系.
所以当我的drawable尚未完全附加到窗口时,我想我会调用我的.start(),但是我/何时/应该如何调用它? @H_404_2@提前致谢!
解决方法
我出来了解决方案.
在自定义TextView中: @H_404_2@(1)首先,你必须决定动画开始和结束的时间.
在自定义TextView中: @H_404_2@(1)首先,你必须决定动画开始和结束的时间.
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); handleAnimationDrawable(true); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); handleAnimationDrawable(false); } private void handleAnimationDrawable(boolean isPlay) { CharSequence text = getText(); if (text instanceof Spanned) { Spanned span = (Spanned) text; ImageSpan[] spans = span.getSpans(0,span.length() - 1,ImageSpan.class); for (ImageSpan s : spans) { Drawable d = s.getDrawable(); if (d instanceof AnimationDrawable) { AnimationDrawable animationDrawable = (AnimationDrawable) d; if (isPlay) { animationDrawable.setCallback(this); animationDrawable.start(); } else { animationDrawable.stop(); animationDrawable.setCallback(null); } } } } }@H_404_2@(2)然后实现自己的Drawable.Callback来触发重绘.
@Override public void invalidateDrawable(Drawable dr) { invalidate(); } @Override public void scheduleDrawable(Drawable who,Runnable what,long when) { if (who != null && what != null) { mHandler.postAtTime(what,when); } } @Override public void unscheduleDrawable(Drawable who,Runnable what) { if (who != null && what != null) { mHandler.removeCallbacks(what); } }