我找到了这个很好的代码片段:Android, Make an image at a URL equal to ImageView's image
并尝试在我正在尝试创建的一个小“屏幕滑块”应用上实现它。当它尝试创建位图时,它会抛出一个异常,说我无法在同一个线程上进行网络调用。然后我尝试创建一个新线程来填充我的imageview,现在它只说创建视图层次结构的原始线程可以触及它的视图。
我不知道下一步该转弯。这是一个扩展Fragment的类,因此没有对ViewGroup的“直接访问”。
这是新线程的代码:
public class MyThread implements Runnable {
ViewGroup vg;
public MyThread(ViewGroup parameter) {
this.vg = parameter;
}
public void run() {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://static.adzerk.net/Advertisers/11239ce559004d9a8e16fe2790630628.png").getContent());
ImageView i = (ImageView)vg.findViewById(R.id.image);
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_screen_slide_page, container, false);
// Set the title view to show the page number.
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.title_template_step, mPageNumber + 1));
Runnable r = new MyThread(rootView);
new Thread(r).start();
return rootView;
}
任何人都可以提供一些建议,告诉我如何在新线程中填充该位图对象,然后传回我的UI线程来填充我的imageview?
TIA。
答案 0 :(得分:0)
我最终使用asynctask来完成这项工作:
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://static.adzerk.net/Advertisers/11239ce559004d9a8e16fe2790630628.png").getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}