[英]Can I save a image dynamically and use it in layouts?
I have a small query, is it possible to get an image dynamically every-time the app is launched over the internet and then that Image can be used to be shown on UI(via xml file)please let me know if this can be achieved in android and with any sample code. 我有一个小的查询,是否有可能在每次通过Internet启动该应用程序时动态获取图像,然后该图像可用于显示在UI(通过xml文件)上,请告诉我是否可以实现在android中以及任何示例代码。 Thanks & Regards.
感谢和问候。
In this case the best way to do it is to load image via HTTP GET, store it in Bitmap
object and inject programmatically into ImageView
element defined in layout. 在这种情况下,最好的方法是通过HTTP GET加载图像,将其存储在
Bitmap
对象中,然后以编程方式将其注入到布局中定义的ImageView
元素中。
You can't override resource image so you cant use @drawable
. 您不能覆盖资源映像,因此不能使用
@drawable
。
Here you have loadBitmap
method that loads image by url and stores it in Bitmap
: How to load an ImageView by URL in Android?
在这里,您有
loadBitmap
方法,该方法通过url加载图像并将其存储在Bitmap
: How to load an ImageView by URL in Android?
Next thing is to inject it into ImageView
: 接下来是将其注入
ImageView
:
ImageView image = (ImageView) findViewById(R.id.image);
Bitmap bitmap = loadBitmap("http://www.android.com/images/logo.png");
image.setImageBitmap(bitmap);
Not possible through XML. 通过XML不可能。
I'd recommend having a placebo bitmap also in case there is no Internet access available at the time. 我建议同时使用安慰剂位图,以防当时无法访问互联网。 Use AsyncTask when downloading.
下载时使用AsyncTask。
new GetAndSetBitmap.execute(url)
private class GetAndSetBitmap extends AsyncTask<String, Void, Bitmap>
{
protected Bitmap doInBackground(String... urls)
{
Bitmap bitmap = loadBitmap(url[0]);
// Used the loadBitmap from other answer. Anything goes wrong
// load a local resource with the same dimensions.
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bm)
{
yourImageView.setImageBitMap(bm);
}
}
Guys found a better solution 伙计们找到了更好的解决方案
try {
ImageView i = (ImageView)findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.