編輯:初階開發
在 ListView 中異步加載圖片是非常實用的一項技術。凡是需要從網絡獲取圖片資源的場景,都建議採用這種方式,用戶體驗會好很多。下面把實現思路與代碼完整梳理一遍。
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache;
public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
// 命中緩存則直接返回,避免重複下載
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};
new Thread() {
@Override
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
public static Drawable loadImageFromUrl(String url) {
URL m;
InputStream i = null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Drawable.createFromStream(i, "src");
}
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}
幾個設計要點:
public class ImageAndText {
private String imageUrl;
private String text;
public ImageAndText(String imageUrl, String text) {
this.imageUrl = imageUrl;
this.text = text;
}
public String getImageUrl() { return imageUrl; }
public String getText() { return text; }
}
public class ViewCache {
private View baseView;
private TextView textView;
private ImageView imageView;
public ViewCache(View baseView) {
this.baseView = baseView;
}
public TextView getTextView() {
if (textView == null) {
textView = (TextView) baseView.findViewById(R.id.text);
}
return textView;
}
public ImageView getImageView() {
if (imageView == null) {
imageView = (ImageView) baseView.findViewById(R.id.image);
}
return imageView;
}
}
ViewCache 的作用是配合 convertView 復用,避免每次都重複 findViewById。
public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {
private ListView listView;
private AsyncImageLoader asyncImageLoader;
public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts, ListView listView) {
super(activity, 0, imageAndTexts);
this.listView = listView;
asyncImageLoader = new AsyncImageLoader();
}
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
View rowView = convertView;
ViewCache viewCache;
if (rowView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.image_and_text_row, null);
viewCache = new ViewCache(rowView);
rowView.setTag(viewCache);
} else {
viewCache = (ViewCache) rowView.getTag();
}
ImageAndText imageAndText = getItem(position);
String imageUrl = imageAndText.getImageUrl();
ImageView imageView = viewCache.getImageView();
imageView.setTag(imageUrl); // 關鍵:用 URL 標記當前行,供回調時精準定位
Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
public void imageLoaded(Drawable imageDrawable, String imageUrl) {
ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
if (imageViewByTag != null) {
imageViewByTag.setImageDrawable(imageDrawable);
}
}
});
if (cachedImage == null) {
imageView.setImageResource(R.drawable.default_image);
} else {
imageView.setImageDrawable(cachedImage);
}
TextView textView = viewCache.getTextView();
textView.setText(imageAndText.getText());
return rowView;
}
}
這裡有個容易忽略的技巧:imageView.setTag(imageUrl)。ListView 的 item 會被反覆復用,如果不做標記,某行下載完成後可能把圖片錯誤地貼到另一行上。回調裡用 findViewWithTag(imageUrl) 反查,就能保證只更新真正對應的那個 item。
<?XML version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Jocky 程式碼保護工具的設定與使用流程
Jocky 是一款用來對 Android 專案做「混碼」(程式碼混淆與保護)的工具,它以 Eclipse 外掛的形式安裝,實際執行的則是一支 Ant 建置腳本。以下是完整
用 OpenGL ES 在 Android 上畫一個旋轉的圓
這是我在 Android 上用 OpenGL ES 畫的第一個圖形,Render 的覆寫部分參考了其他同學的程式碼。以下完整程式碼可直接運行。 public clas
Android 本地化開發技巧
Android 可透過資源目錄自動適配語言與螢幕。語言方面,可在 res 下建立:values-zh-rCN:簡體中文。values-ja:日文。values-fr:法文
Android 特色開發:帳戶管理(AccountManager)實作解析
本文節選自機械工業出版社《Android 應用開發揭秘》,作者楊豐盛。該書涵蓋 Android 框架、組件、使用者介面、遊戲開發、資料儲存、多媒體與網路開發等基礎,並深入