自定义ImageView性能

时间:2016-09-17 20:46:27

标签: android performance

我创建了一个自定义ImageView - 它的目的是从互联网上获取图像。它的声明如下:

public class WebImageView extends ImageView {

    private String mUrl;

    private Bitmap mCachedBitmap;

    public String getUrl() { return mUrl; }
    public void setUrl(String url) {
        mUrl = url;

        if (mCachedImage == null) {
            new ImageDownloader(this).execute(mUrl);
        } else {
            setImageBitmap(mCachedImage);
        }
    }

    public WebImageView(Context context) {
        super(context);
    }

    public WebImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WebImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public WebImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {

        private final ImageView mView;

        public ImageDownloader(ImageView view) {
            mView = view;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            String url = params[0];
            Bitmap image = null;

            try {
                InputStream in = new java.net.URL(url).openStream();
                image = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error Message", e.getMessage());
                e.printStackTrace();
            }

            return image;
        }

        protected void onPostExecute(Bitmap result) {
            mView.setImageBitmap(result);
        }

    }

}

它的使用非常简单:

<com.myapp.views.controls.WebImageView
            android:layout_width="@dimen/restaurantLogoWidth"
            android:layout_height="@dimen/restaurantLogoHeight"
            url="@{restaurant.model.logoUrl}"
            style="@style/ImageView" />

上面的xml放在android.support.v7.widget.RecyclerView内。问题是当我在我的项目列表上滚动(或执行一些动画)时,它表现得非常糟糕,这意味着滚动(或动画)不平滑。有什么建议可以在这里改变,以使其表现更好吗?

1 个答案:

答案 0 :(得分:1)

不要构建自定义视图来执行此操作。只需使用Glide图像加载库。 https://github.com/bumptech/glide

ImageView targetImageView = (ImageView) findViewById(R.id.imageView);  
String internetUrl = "http://i.imgur.com/DvpvklR.png";

Glide  
.with(context)
.load(internetUrl)
.into(targetImageView);

https://futurestud.io/tutorials/glide-getting-started

Recyclerview Adapter and Glide - same image every 4-5 rows