我有一个与 Google Cloud Endpoints 配合使用的 Android 应用。我的一项 Activity 向数据存储发送请求以获取 Message
实体列表。
该实体有一个包含缩略图的 byte[]
字段。还有其他两个字段:作者和时间戳。
然后,该 Activity 必须显示一个 ListView,其中显示缩略图以及作者和时间戳字段。这是我当前的代码,仅显示我的一些资源图像和作者/时间戳字段:
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 });
并使用 Binder :
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;
}
});
关于java - 如何将 ImageView 与 SimpleAdapter 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28572603/