문제
GalleryView 사용에 대한 질문이 있습니다.
처음에는 Drawable Directory에서 표시하기 위해 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 $ romwromwrongthreadexception : View Hierarchy를 생성 한 원래 스레드만이 뷰를 터치 할 수 있습니다.
아이디어가 있습니까?
감사
해결책
당신은 구현해야합니다 onPostExecute()
UI와 상호 작용하는 코드를 이동하십시오 (아마도 notifyDataSetChange()
) 그 방법에. Android는 GUI와의 상호 작용이 UI 스레드에서 발생해야합니다.
다른 팁
이를 위해서는이 코드를 Async Task의 OnPostExecute () 메소드에 넣어야합니다.
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