【问题标题】:How to load animation-lists with Picasso?如何使用毕加索加载动画列表?
【发布时间】:2017-03-29 21:43:38
【问题描述】:

将图像加载到我的应用程序时出现内存不足异常。我集成了毕加索来加载图像,但下面的代码不适用于 AnimationDrawable 的动画列表。动画为空:

Picasso.with(this).load(R.drawable.qtidle).into(qtSelectButton);
qtIdleAnimation = (AnimationDrawable)qtSelectButton.getDrawable();
if (qtIdleAnimation != null)
    qtIdleAnimation.start();

AnimationDrawable 有效,如果我在没有 Picasso 的情况下使用此代码:

qtIdleAnimation = new AnimationDrawable();
qtIdleAnimation.setOneShot(false);
for (int i = 1; i <= 7; i++) {
    int qtidleId = res.getIdentifier("qtidle" + i, "drawable", this.getPackageName());
    qtIdleAnimation.addFrame(res.getDrawable(qtidleId), 100);
}
qtSelectButton.setImageDrawable(qtIdleAnimation);
if (qtIdleAnimation != null)
    qtIdleAnimation.start();

但此代码会导致内存不足异常。是否可以使用 Picasso 加载动画列表?

【问题讨论】:

  • 你找到什么了吗?请回复。
  • 抱歉,一直没弄明白,然后我放弃了这个项目。

标签: android picasso animationdrawable


【解决方案1】:

Picasso 无法将xml 文件中定义的animation-list 直接加载到视图中。不过自己模仿毕加索的基本行为也不是太难:

1.像您一样以编程方式定义和启动动画,但在 AsyncTask 中以避免内存不足异常

Resources res = this.getResources();
ImageView imageView = findViewById(R.id.image_view);
int[] ids = new int[] {R.drawable.img1, R.drawable.img2, R.drawable.img3};

创建AsyncTask的子类:

private class LoadAnimationTask extends AsyncTask<Void, Void, AnimationDrawable> {
    @Override
    protected AnimationDrawable doInBackground(Void... voids) {
        // Runs in the background and doesn't block the UI thread
        AnimationDrawable a = new AnimationDrawable();
        for (int id : ids) {
            a.addFrame(res.getDrawable(id), 100);
        }
        return a;
    }
    @Override
    protected void onPostExecute(AnimationDrawable a) {
        // This will run once 'doInBackground' has finished
        imageView.setImageDrawable(a);
        if (a != null)
            a.start();
    }
}

然后运行任务将动画加载到您的 ImageView 中:

new LoadAnimationTask().execute()

2。如果您的可绘制对象比您的视图大,请仅以所需的分辨率加载可绘制对象来节省内存

而不是直接添加drawable:

a.addFrame(res.getDrawable(id), 100);

添加它的缩小版:

a.addFrame(new BitmapDrawable(res, decodeSampledBitmapFromResource(res, id, w, h));

其中wh 是视图的尺寸,decodeSampledBitmapFromResource() 是Android 官方文档中定义的方法(Loading Large Bitmaps Efficiently

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 2014-09-09
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 2016-07-25
    相关资源
    最近更新 更多