gpt4 book ai didi

android - 在 TextView 中动态加载 AnimationDrawable

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:07:15 25 4
gpt4 key购买 nike

我需要用图像替换 a 中的文本短语,然后将其附加到 TextView。对于常规 Drawable,这没有问题,但是当 Drawable 是 AnimationDrawable 时,我不知道何时何地调用 .start();

这就是我将文本附加到 TextView 的方式:

textview.append(Html.fromHtml(textWithHtmlImgTags, imagegetter, null));

textWithHtmlImgTags 中的图片标签使用 imagegetter 替换:

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, 0, dra.getIntrinsicWidth(), dra.getIntrinsicHeight());
dra.start(); // This doesn't work..

return dra;
}

Drawable dr = res.getDrawable(sRes.get(source));
dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
return dr;
}

};

我的 AnimationDrawables 已添加,但它们不是动画(它们卡在第 1 帧)。

在文档中它说:

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.

由于图像是动态添加的,我认为它与 onCreate() 没有任何关系。所以我想当我的可绘制还没有完全附加到窗口时,我调用了我的.start(),但是在哪里/何时/如何应该我叫它?

提前致谢!

最佳答案

我想出了解决方案。在您的自定义 TextView 中:

(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);
}
}
}
}
}

(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);
}
}

关于android - 在 TextView 中动态加载 AnimationDrawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9418530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com