我创建了一个自定义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