我有一个textView。在我的代码中,我在其中添加了一些文本行。我还想在这些行之间显示来自外部URL(而不是我的资源文件夹)的一些图像。每件事都是动态的,即生成的文本和图像URL将在流上生成。所以我必须通过我的代码获取图像并添加它。
想知道是否有办法在文本视图中插入来自外部URL的图像?也欢迎任何更好的方法。
答案 0 :(得分:3)
你必须和asynctask一起使用它,
在doInbackground()
中打开连接
在onPostExecute()
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL("ur Image URL");
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
Drawable d =new BitmapDrawable(bm);
d.setId("1");
textview.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);// wherever u want the image relative to textview
} catch (IOException e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
希望有所帮助
答案 1 :(得分:0)
您可能希望使用asynctask来抓取图像。这将在您的其他任务的后台运行。您的代码可能如下所示:
public class ImageDownloader extends AsyncTask<String, Integer, Bitmap>{
private String url;
private final WeakReference<ImageView> imageViewReference;
//a reference to your imageview that you are going to load the image to
public ImageDownloader(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(String... arg0) {
if(isCancelled())
return null;
Bitmap retVal;
url = arg0[0];//this is the url for the desired image
...download your image here using httpclient or another networking protocol..
return retVal;
}
@Override
protected void onPostExecute(Bitmap result) {
if (isCancelled()) {
result = null;
return;
}
ImageView imageView = imageViewReference.get();
imageView.setImageBitmap(result);
}
@Override
protected void onPreExecute() {
...do any preloading you might need, loading animation, etc...
}