[英]How to use ImageView with SimpleAdapter?
我有一个使用Google Cloud Endpoints的Android应用程序。 我的一项活动将请求发送到数据存储,以获取Message
实体列表。 这个实体有一个byte[]
字段,其中包含缩略图。 还有其他两个字段:“作者”和“时间戳记”。
然后,活动必须显示一个ListView,其中同时显示了缩略图以及author和timestamp字段。 这是我当前的代码,仅显示我的一些资源图片和author / timestamp字段:
messages_list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/messages_thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginTop="7dp"
android:background="@null"
android:src="@drawable/photo" />
<TextView
android:id="@+id/messages_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/messages_thumbnail"
android:layout_marginLeft="7dp"
android:layout_toRightOf="@id/messages_thumbnail"
android:textColor="#303030" />
<TextView
android:id="@+id/messages_timestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/messages_thumbnail"
android:layout_alignParentRight="true"
android:layout_marginRight="7dp"
android:textColor="#303030" />
现在,我使用Hashmap列表管理SimpleAdapter的部分:
final List<HashMap<String, Object>> messages = new ArrayList<HashMap<String, Object>>();
List<Message> listmessages = messagesCollection.getItems();
for (Message message : listmessages) {
HashMap<String, Object> element;
element = new HashMap<String, Object>();
byte[] miniature = message.decodeMiniature(); //what to do with this?
element.put("AUTHOR", message.getAuthor());
element.put("TIMESTAMP", message.getTimestamp());
messages.add(element);
}
ListAdapter simpleAdapter = new SimpleAdapter(context,
messages, R.layout.messages_list_layout,
new String[] { "AUTHOR", "TIMESTAMP"},
new int[] { R.id.messages_author, R.id.messages_timestamp });
listView_messages.setAdapter(simpleAdapter);
您应该使用BitmapFactory将字节数组解码为位图,并将其存储为使用新键进行映射(例如“ AUTHOR”,“ TIMESTAMP”)
例如:
byte[] miniature = message.decodeMiniature();
Bitmap image = BitmapFactory.decodeByteArray(miniature, 0, miniature.length);
element.put("IMAGE", image);
...
ListAdapter simpleAdapter = new SimpleAdapter(context,
messages, R.layout.messages_list_layout,
new String[] { "AUTHOR", "TIMESTAMP", "IMAGE"},
new int[] { R.id.messages_author, R.id.messages_timestamp, R.id.messages_thumbnail });
并使用粘合剂:
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object data,String textRepresentation)
{
if((view instanceof ImageView) & (data instanceof Bitmap))
{
ImageView iv = (ImageView) view;
Bitmap bm = (Bitmap) data;
iv.setImageBitmap(bm);
return true;
}
return false;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.