Androidギャラリーの更新画像を表示します
-
19-09-2019 - |
質問
GalleryViewの使用について質問があります。
最初は、描画可能なディレクトリから表示するように5つの「デフォルト画像」を設定しました。
しかし、その後、画像をダウンロードし、保存してギャラリーに表示する非同期タスクを実行したいと思います。
そのために、次のアダプターを作成しました。
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private ArrayList<Integer> mImageIds = new ArrayList<Integer>();
private ArrayList<Drawable> mImageDrawables = new ArrayList<Drawable>();
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public void setPlaces(int count) {
for (int i = 0; i < count; i++) {
mImageIds.add(R.drawable.tournoimg);
mImageDrawables.add(null);
}
}
public void setDrawable(String resource, int position) {
Drawable image = Drawable.createFromPath(resource);
mImageDrawables.add(position, image);
}
public int getCount() {
return mImageIds.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
if (mImageDrawables.get(position) == null)
i.setImageResource(mImageIds.get(position));
else
i.setImageDrawable(mImageDrawables.get(position));
i.setLayoutParams(new Gallery.LayoutParams(60, 78));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}
そして、次の非同期タスク
private class FillImages extends AsyncTask<ArrayList<Place>, Void, Void> {
protected Void doInBackground(ArrayList<Place>... listplaces) {
ArrayList<Place> places = listplaces[0];
Iterator<Place> it = places.iterator();
int position = 0;
while (it.hasNext()) {
Place p = it.next();
saveImage(p.getImage(), p.getURLImage());
// Gallery g = (Gallery) findViewById(R.id.gallery);
mImageAdapter.setDrawable(p.getImage(), position);
position++;
mImageAdapter.notifyDataSetChanged();
}
return (null);
}
しかし、私がそれを実行するとき、私はこのエラーがあります:原因:android.view.viewroot $ calldfromwrongthreadexception:ビュー階層を作成した元のスレッドのみがそのビューに触れることができます。
何か案が?
ありがとう
解決
実装する必要があります onPostExecute()
UIと対話するコードを移動します(おそらく notifyDataSetChange()
)その方法に。 Androidでは、GUIとの相互作用がUIスレッドから発生することが必要です。
他のヒント
そのためには、このコードをonpostexecute()Asyncタスクの方法に入れる必要があります。
ArrayList<Place> places = listplaces[0];
Iterator<Place> it = places.iterator();
int position = 0;
while (it.hasNext()) {
Place p = it.next();
saveImage(p.getImage(), p.getURLImage());
// Gallery g = (Gallery) findViewById(R.id.gallery);
mImageAdapter.setDrawable(p.getImage(), position);
position++;
mImageAdapter.notifyDataSetChanged();
}
所属していません StackOverflow