从ImageView Drawable获取资源ID或InputStream

时间:2013-12-30 10:20:58

标签: android view imageview

我正在开发一个GifView类,扩展android.view.ImageView以在Android中显示动画gif。

问题是从XML布局获取android:src="@drawable/myGif"以自动将其加载到Movie中。当我覆盖setImageDrawable(Drawable drawable)以拦截默认的android行为时,我有两种不同的方法:从@drawable/myGif获取id资源并保存以供以后使用,或者在Movie中按需加载它。但是对于后一种选择,我需要将InputStream中未使用的压缩方法中的Drawable从Bitmap类转换为可以安全的GIF层。

我该怎么做?

public class GifView extends ImageView {

    ...
private Movie movie;
private int resId;

public GifView(Context context) {

    super(context);
    this.context = context;
}

public GifView(Context context, AttributeSet attrs) {

    super(context, attrs);
    this.context = context;
}

public GifView(Context context, AttributeSet attrs, int defStyle) {

    super(context, attrs, defStyle);
    this.context = context;
}

@Override
public void setImageDrawable(Drawable drawable) {

    // ONE OF THOSE WAYS TO DO

    // this.redId = ...

    // this.movie = Movie.decodeStream(...);
}

    ...
}

1 个答案:

答案 0 :(得分:0)

好的,你可以自动完成,但它真的付出了吗?

public class GifImageView extends ImageView {
    private final static String TAG = "GifImageView";

    public GifImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        int[] attrArray = {
                android.R.attr.src
        };
        TypedArray a = context.obtainStyledAttributes(attrs, attrArray);
        int id = a.getResourceId(0, 0);
        a.recycle();

        if (id != 0) {
            try {
                Drawable d = new GifDrawable(getResources(), id);
                setImageDrawable(d);
            } catch (Exception e) {
                Log.d(TAG, "GifImageView " + e.getMessage());
            }
        }
    }

    class GifDrawable extends Drawable implements Runnable {
        ...
    }
}