package app.test;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.AttributeSet;
import android.widget.ImageView;
class WebImageView extends ImageView {
private Drawable mPlaceholder, mImage;
public WebImageView(Context context, AttributeSet attrs, int defaultStyle) {
super(context, attrs, defaultStyle);
}
public void setPlaceholderImage(Drawable drawable) {
mPlaceholder = drawable;
if (mImage == null) {
setImageDrawable(mPlaceholder);
}
}
public void setPlaceholderImage(int resid) {
mPlaceholder = getResources().getDrawable(resid);
if (mImage == null) {
setImageDrawable(mPlaceholder);
}
}
public void setImageUrl(String url) {
DownloadTask task = new DownloadTask();
task.execute(url);
}
private class DownloadTask extends AsyncTask {
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
try {
BufferedInputStream bis = new BufferedInputStream((new URL(url)).openConnection().getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
byte[] imageData = baf.toByteArray();
return BitmapFactory.decodeByteArray(imageData, 0,imageData.length);
} catch (Exception exc) {
return null;
}
}
@Override
protected void onPostExecute(Bitmap result) {
mImage = new BitmapDrawable(result);
if (mImage != null) {
setImageDrawable(mImage);
}
}
};
}
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebImageView imageView = (WebImageView) findViewById(R.id.webImage);
imageView.setPlaceholderImage(R.drawable.icon);
imageView.setImageUrl("http://yourdomain.com/a.gif");
}
}
//main.xml
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
android:id="@+id/webImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>