2016-09-17 70 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

我正在尋找類似的東西,但找不到這一個。謝謝! –