我有带有项目的 ListView,每个项目都有 5 个 TextView,其中一个 TextView 从 Html.fromHtml 函数中获取他的文本,我使用 ImageGetter 函数来处理 HTML 中的 img 标签,图像下载异步,而图像下载我想显示 AnimationDrawable(循环进度条)。
这是我的 ImageGetter 实现:
holder.CommentText.setText(Html.fromHtml(commentObj.getComment(), new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable d = null;
if(UserSettings.LoadImages)
{
if(commentObj.getImages()==null)
{
commentObj.setImages(new HashMap<String, Drawable>());
}
String imageLink=source;
if(!imageLink.contains("http://"))
imageLink="http://rotter.net"+source;
if(commentObj.getImages().containsKey(imageLink))
{
d=commentObj.getImages().get(imageLink);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
}
else
{
AnimationDrawable animated=(AnimationDrawable)context.getResources().getDrawable(R.anim.image_loading);
animated.setBounds(0, 0, animated.getIntrinsicWidth(), animated.getIntrinsicHeight());
//animated.start();
commentObj.getImages().put(imageLink, animated);
DownloadImage downImg=new DownloadImage(commentObj, imageLink,v,adapter,Width,context.getResources());
holder.CommentText.onAttachedToWindow();
downImg.execute(new String[] { imageLink } );
return animated;
}
}
return d;
}
},null ));
经过一番阅读,我创建了新的自定义 TextView 类:
public class NewTextView extends TextView {
private Handler mHandler=new Handler();
public NewTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public NewTextView(Context context,AttributeSet attributeSet) {
super(context,attributeSet);
// TODO Auto-generated constructor stub
}
@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);
}
}
}
}
}
@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);
}
}
}
NewTextView 类负责启动和停止 AnimationDrawable,结果是有的 AnimationDrawable 运行正常(循环进度条)而有的 AnimationDrawable 根本没有运行,它们只显示 AnimationDrawable 项中的第一个 Drawable。
可能是什么问题?为什么不是所有的 AnimationDrawables 都能正常运行?