It is possible to create a imageButton
and within it put an image of internet . Can I do this with webView
, but can it do with imageButton
?
It is possible to create a imageButton
and within it put an image of internet . Can I do this with webView
, but can it do with imageButton
?
I think the simplest way is this:
URL imageUrl = new URL("url_da_imagem");
Bitmap imagem = BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream());
meuImageButton.setImageBitmap(imagem);
Source SOen
However, the correct thing is to do this in an AsyncTask :
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageButton imageButton;
public DownloadImageTask(ImageButton imageButton) {
this.imageButton = imageButton;
}
protected Bitmap doInBackground(String... urls) {
URL imageUrl = null;
try {
imageUrl = new URL(urls[0]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap imagem = null;
try {
imagem = BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imagem;
}
protected void onPostExecute(Bitmap result) {
imageButton.setImageBitmap(result);
}
}
To put the image in your ImageButton do:
ImageButton imageButton = (ImageButton) findViewById(R.id.doSeuImageButton);
new DownloadImageTask(imageButton).execute("url_da_imagem");
You must add the following permission to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
First you need to download this image because there is no direct way to inform a URL directly in the src
property, for example.
You can have a method like this to download and get a Drawable
:
public Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
And then, just set the property of ImageButton
:
btn.setImageResource(drawableFromUrl("http://..."));
I have not tested, but you will probably have to do this in a thread other than UI
.