How To Set Image Button Resource From Web Url In Android?
I have an image button and would like to set background image from internet URL. I don't want to save background picture into SD card instead my image button's image needs to be UR
Solution 1:
Never tried this but hope fully this will work with you
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, saveFilename);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
returnnull;
} catch (IOException e) {
e.printStackTrace();
returnnull;
}
}
and for image view
ImageView IV= (ImageView)findViewById(R.id.imageId);
Drawabledrw= ImageOperations(this,url,filename)
IV.setBackgroundDrawable(drw)
get URL
public Object fetch(String address)throws MalformedURLException,IOException {
URLurl=newURL(address);
Objectcontent= url.getContent();
return content;
}
Solution 2:
First you have to download your Image as Drawable: Android Drawable Images from URL
and after that set it as background drawable
button.setBackgroundDrawable(drawable)
Solution 3:
Try this
Bitmap bitmap;
classloadImageextendsAsyncTask<Void , Void, Void>{
@OverrideprotectedvoidonPreExecute() {
super.onPreExecute();
}
@Overrideprotected Void doInBackground(Void... params) {
URLurl=newURL(stringURL);
URIuri=newURI(url.getProtocol(), url.getHost(),
url.getPath(), url.getQuery(), null);
HttpURLConnectionconnection= (HttpURLConnection) uri
.toURL().openConnection();
connection.setDoInput(true);
connection.connect();
InputStreaminput= connection.getInputStream();
ByteArrayOutputStreambyteBuffer=newByteArrayOutputStream();
intbufferSize=1024;
byte[] buffer = newbyte[bufferSize];
intlen=0;
while ((len = input.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
byte[] img = byteBuffer.toByteArray();
byteBuffer.flush();
byteBuffer.close();
input.close();
bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
returnnull;
}
@OverrideprotectedvoidonPostExecute(Void result) {
super.onPostExecute(result);
ImageButtonimage_btn= (ImageButton)findViewById(R.id.your_image_button_id);
image_btn.setImageBitmap(bitmap);
}
}
Post a Comment for "How To Set Image Button Resource From Web Url In Android?"