2016-09-17 38 views
0

我创建了一个自定义ImageView - 它的目的是从互联网上获取图像。它的声明看起来如下:自定义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

我的建议是使用[许多现有图像加载可用于Android库]的一个(http://android-arsenal.com/tag/ 46),而不是重新重新重新重新重新发明车轮。除此之外,你是单线程的,假设你的'targetSdkVersion'是13或更高。你也没有考虑回收,不执行任何图像缓存等。 – CommonsWare

回答

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

+0

我正在寻找类似的东西,但找不到这一个。谢谢! –