我創建了一個自定義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
內。問題是,當我滾動(或執行一些動畫)在我的項目列表上時,它執行非常糟糕,這意味着滾動(或動畫)不光滑。任何建議我可以在這裏改變,使其表現更好?
我的建議是使用[許多現有圖像加載可用於Android庫]的一個(http://android-arsenal.com/tag/ 46),而不是重新重新重新重新重新發明車輪。除此之外,你是單線程的,假設你的'targetSdkVersion'是13或更高。你也沒有考慮回收,不執行任何圖像緩存等。 – CommonsWare