效果图:
此程序主要的知识点是:SimpleAdapter本身是不支持网络图片的, 如果在Map.put(a,b)中 b为一个Bitmap,程序不会报红色字体,而是在控制台输出绿色的字体,如下
05-10 15:46:45.474: I/System.out(846): resolveUri failed on bad bitmap uri: android.graphics.Bitmap@43e40c08
要想实现显示网络图片其实很简单,使用SimpleAdapter中的方法simpleAdapter.setViewBinder()。
simpleAdapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if (view instanceof ImageView && data instanceof Bitmap) {
ImageView iv = (ImageView) view;
iv.setImageBitmap((Bitmap) data);
return true;
}
return false;
}
});
new SimpleAdapter(MainActivity.this,getData(), R.layout.t, new String[] { "images" },new int[] { R.id.ImageVIew_main });
有三个参数view,data,textRepresentation,说说前两个参数,view 是你自定义布局(如上 R.layout.t)中所有的组件,程序会遍历一边布局中的组件,data是你传的
list
既然是网络图片,那就需要权限
代码如下:
MainActivity.java
public class MainActivity extends ActionBarActivity {
ListView listView;
List> data;
String str[] = { "", //自己添加图片网址 h t t p ://
"",
"",
"" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.LV_main);
SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this,
getData(), R.layout.t, new String[] { "images" },
new int[] { R.id.ImageVIew_main });
simpleAdapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if (view instanceof ImageView && data instanceof Bitmap) {
ImageView iv = (ImageView) view;
iv.setImageBitmap((Bitmap) data);
return true;
}
return false;
}
});
listView.setAdapter(simpleAdapter);
}
public List> getData() {
data = new ArrayList>();
for (int i = 0; i < str.length; i++) {
Map map = new HashMap();
map.put("images", returnBitMap(str[i]));
data.add(map);
}
return data;
}
public Bitmap returnBitMap(String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
activity_main.xml
自定义布局文件
t.xml
补充说明:
以为listview+SimpleAdapter不会有人使用,只是用来记录了我成长的印记,但是,每隔一段时间就会有人来评论,觉得有必要更新一下,以适应android发展。
就上面代码,做出调整。废弃returnBitMap方法。
更改setViewValue方法并使用glide框架来加载图片。
导入glide框架
dependencies {
..........
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
}
修改setViewValue
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if (view instanceof ImageView) {
ImageView iv = (ImageView) view;
Glide.with(iv.getContext()).load((String) data).into(iv);
return true;
}
return false;
}