1. 异步加载
public class MainActivity extends Activity {
private ArrayList<Bean> beans = new ArrayList<Bean>();
ImageAdapter adapter ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (int i = 0; i < 15; i++)
{
Bean bean = new Bean();
// 初始为本地icon图片
bean.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
beans.add(bean);
}
adapter = new ImageAdapter();
ListView listView = new ListView(this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
setContentView(listView);
// 构造时,传入adapter,用户更新数据UI
new ImageLoadTask(this, adapter).execute();
}
class Bean
{
private Bitmap bitmap;
public void setBitmap(Bitmap bitmap)
{
this.bitmap = bitmap;
return ;
}
public Bitmap getBitmap()
{
return bitmap;
}
}
class ImageAdapter extends BaseAdapter
{
@Override
public int getCount()
{
// TODO Auto-generated method stub
return beans.size();
}
@Override
public Bean getItem(int position)
{
// TODO Auto-generated method stub
return beans.get(position);
}
@Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView img = new ImageView(MainActivity.this);
Bean b = beans.get(position);
if ( b.getBitmap() != null)
{
img.setImageBitmap(b.getBitmap());
}
return img;
}
}
// 异步线程
class ImageLoadTaskextends AsyncTask
{
ImageAdapter adapter;
public ImageLoadTask(Context context, ImageAdapter adapter)
{
this.adapter = adapter;
}
@Override
protected Object doInBackground(Object... params)
{
for (int i = 0; i < adapter.getCount(); i++)
{
Bean b = adapter.getItem(i);
Bitmap bitmap = BitmapFactory.decodeStream(Request.HandlerData
("http://avatar.profile.csdn.net/A/E/5/2_piaopiaohu123.jpg")); // url
b.setBitmap(bitmap);
// 更新UI,调用onProgressUpdate
publishProgress();
}
return null;
}
@Override
protected void onProgressUpdate(Object... values)
{
adapter.notifyDataSetChanged();
}
}
}
2. // 从网络中获取数据流
public class Request {
public static InputStream HandlerData(String url) {
InputStream inStream=null;
try {
URL feedUrl = new URL(url);
// URLConnection conn = feedUrl.openConnection();
// conn.setConnectTimeout(10 * 1000);
// inStream = conn.getInputStream();
// 或者可以这样使用url读取网络图片
inStream = feedUrl.openStream();
} catch (Exception e) {
Log.i("bitmap","exception");
e.printStackTrace();
}
return inStream;
}
}
3. AndroidManifext.xml文件中添加访问网络的权限
<uses-permission android:name="android.permission.INTERNET" />