问题描述
有人可以帮我吗? 我正在构建一个基于聊天的应用程序,并且有一个选项卡用来显示用户所属的群组聊天,因此,当我从Firebase检索这些群组时,假设只携带用户参与的群组。我设法做到了,但是问题是即使没有信息,布局也被夸大了。如下图所示。
The third empty block was not supposed to show up
This is a pic of the group node on Firebase
这是groupRef实例...
groupRef = FirebaseDatabase.getInstance().getReference().child("groups");
这是我的onBindViewHolder ...
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Contact>().setQuery(groupRef,Contact.class).build();
final FirebaseRecyclerAdapter<Contact,GroupViewHolder> adapter = new FirebaseRecyclerAdapter<Contact,GroupViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull final GroupViewHolder holder,int position,@NonNull Contact contact) {
final String groupId = getRef(position).getKey();
final String[] retimage = {"default_image"};
groupRef.child(groupId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
if (dataSnapshot.hasChild(userId)) {
if (snapshot.hasChild("image")) {
retimage[0] = snapshot.child("image").getValue().toString();
Picasso.get().load(retimage[0]).into(holder.groupImage);
}
final String groupName = snapshot.child("name").getValue().toString();
holder.groupName.setText(groupName);
holder.groupStatus.setText("Last seen: ");
holder.itemView.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
@NonNull
@Override
public GroupViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup,int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.contact_book_list_item,viewGroup,false);
GroupViewHolder viewHolder = new GroupViewHolder(view);
return viewHolder;
}
};
这是视图持有者类
public static class GroupViewHolder extends RecyclerView.ViewHolder {
CircleImageView groupImage;
TextView groupName,groupStatus;
public GroupViewHolder(@NonNull View itemView) {
super(itemView);
groupName = itemView.findViewById(R.id.textName);
groupStatus = itemView.findViewById(R.id.textPhone);
groupImage = itemView.findViewById(R.id.imagePersonIcon);
}
}
解决方法
您得到的其他结果完全正常。您正在此处检查groupId子级的子级:
groupRef.child(groupId).addValueEventListener(new ValueEventListener() {
...
}
,那里有3个孩子,所以一切正常。现在,如果您只想显示其中具有该特定用户名的groupId的chikdren,则必须对其进行过滤,然后将其发送到适配器。因此,将addValueEventListener {}完全从视图绑定器中取出,获取groupId中所有可用的组,进行遍历,然后将其中包含用户名的组添加到arraylist中,然后将arraylist传递给适配器并显示它们在您的onBindViewHolder {}
中