在 Thread.run() 中直接 linearLayout.addView(imageView) 導致 ViewRootImpl$CalledFromWrongThreadException,且 gURL 陣列因異步未填充而為 null。
for 迴圈在網路回調完成前執行,gURL[i] 尚未賦值。// 在網路回調成功後
runOnUiThread(() -> {
for (int i = 0; i < gURL.length; i++) {
if (gURL[i] != null) {
ImageView iv = new ImageView(MainActivity.this);
// 建議使用圖片載入庫,此處示範同步下載(僅教學)
new Thread(() -> {
Bitmap bmp = downloadBitmap(gURL[i]);
runOnUiThread(() -> iv.setImageBitmap(bmp));
}).start();
linearLayout.addView(iv);
}
}
});
// build.gradle
implementation 'com.github.bumptech.glide:glide:4.16.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
// Activity 中
for (String url : gURL) {
if (url != null) {
ImageView iv = new ImageView(this);
linearLayout.addView(iv);
Glide.with(this).load(url).into(iv); // 自動處理執行緒、快取、佔位圖
}
}
runOnUiThread、Handler、View.post、Activity.runOnUiThread)。RecyclerView + GridLayoutManager,避免 OOM。