问题描述
我有一个 url 传递给一个活动,我试图从 url 全屏显示图像,但是它引发了一个主网络线程异常.
I have an url passed to an activity and I am trying to show the image from the url full screen, however it throws a main network thread exception.
据我所知,我相信我必须将该方法放在异步任务中,但我似乎根本无法理解它.那么如何将这个方法放在异步任务中呢?
From what I can find I believe I have to put the method in an async task however I cannot seem to make sense of it at all. So how would I put this method in an async task?
FullScreenImageView.java
FullScreenImageView.java
public class FullscreenImageView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = getIntent().getStringExtra("SelectedImageURL");
try {
ImageView i = (ImageView)findViewById(R.id.imgView);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐答案
应该是这样的.在 doInBackground
你得到图像,在 onPostExecute
你设置它
It should be something like this.
In the doInBackground
you get the image, and in the onPostExecute
you set it
private class DownloadFilesTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(urls[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
ImageView i = (ImageView)findViewById(R.id.imgView);
i.setImageBitmap(bitmap);
}
}
然后,在 onCreate
方法中调用它
Then, you call it inside your onCreate
method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = getIntent().getStringExtra("SelectedImageURL");
new DownloadFilesTask ().execute(url);
}
这篇关于如何在异步任务中实现此图像视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!