我正在尝试使用ParseQueryAdapter在列表视图中显示用户名和照片.我有以下课程:User和Post.
我在这里设置:
String[] postsObjectIds = some_string_array
ParseQueryAdapter<Post> adapter = new ParseQueryAdapter<Post>(getActivity(), new ParseQueryAdapter.QueryFactory<Post>() {
public ParseQuery<Post> create() {
ParseQuery<Post> query = Post.getQuery();
query.include("User");
query.whereContainedIn("objectId", Arrays.asList(postsObjectIds));
return query;
}
});
adapter.setTextKey("username");
adapter.setimageKey("photo");
adapter.setPlaceholder(getResources().getDrawable(R.drawable.some_drawable));
ListView listView = (ListView) rootView.findViewById(R.id.post_list_view);
listView.setAdapter(adapter);
Post类有一个名为photo的列,而User类有一个名为username的列.列表视图未显示用户名.
解决方法:
我在解析帮助论坛上找到了答案:
ParseQueryAdapter setTextKey for relational object
接受的答案说使用自定义的ParseQueryAdapter< T>.并覆盖getItemView.
例如,在片段的onCreateView方法中,我初始化了适配器并进行了设置(postsObjectIds是某些String []):
PostViewListViewAdapter adapter = new PostViewListViewAdapter(getActivity(), postsObjectIds);
ListView listView = (ListView) rootView.findViewById(R.id.post_list_view);
listView.setAdapter(adapter);
这是我的适配器(PostViewListViewAdapter):
public class PostViewListViewAdapter extends ParseQueryAdapter<Post> {
private final String[] mPostsObjectIds;
public PostViewListViewAdapter(Context context, final String[] postsObjectIds) {
super(context, new ParseQueryAdapter.QueryFactory<Post>(){
public ParseQuery<Post> create() {
ParseQuery<Post> query = Post.getQuery();
query.include("User");
query.whereContainedIn("objectId", Arrays.asList(postsObjectIds));
return query;
}
});
this.mPostsObjectIds = postsObjectIds;
}
@Override
public View getItemView(Post post, View v, ViewGroup parent) {
if(v == null) {
v = View.inflate(getContext(), R.layout.list_item_post_view, null);
}
super.getItemView(post, v, parent);
final TextView usernameTextView = (TextView) v.findViewById(R.id.username_text_view);
post.getCreator().fetchIfNeededInBackground(new GetCallback<ParseUser>() {
@Override
public void done(ParseUser user, ParseException e) {
usernameTextView.setText(user.getUsername());
}
});
return v;
}
}