在我的博客应用程序中发布详细信息Activity
我添加了评论列表,其中包含简单的RecyclerView
适配器工作正常,但我无法添加删除按钮以进行评论,因此移至 FireBase < / strong> RecyclerView
现在我有很多问题
活动代码:
mCommentsRecycler.setLayoutManager(mlinearLayoutManager);
}
@Override
public void onStart() {
super.onStart();
// Add value event listener to the post
// [START post_value_event_listener]
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
// [START_EXCLUDE]
// mAuthorView.setText(post.author);
mTitleView.setText(post.title);
mBodyView.setText(post.body);
final String formImage = String.valueOf(post.postDetailPic);
// [END_EXCLUDE]
if (formImage.length() > 0) {
Picasso.with(getApplicationContext()).load(formImage)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(postPic, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
//Try again online if cache failed
Picasso.with(getApplicationContext())
.load(formImage)
//.error(R.drawable.ic_warning_black_24dp)
.into(postPic, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Log.v("Picasso", "Could not fetch image");
}
});
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// [START_EXCLUDE]
Toast.makeText(PostDetailActivity.this, "Failed to load post.",
Toast.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
};
mPostReference.addValueEventListener(postListener);
// [END post_value_event_listener]
// Keep copy of post listener so we can remove it when app stops
mPostListener = postListener;
// Listen for comments
mAdapter = new CommentAdepter(Comment.class, CommentViewHolder.class, R.layout.item_comment, mCommentsReference, this);
mCommentsRecycler.setAdapter(mAdapter);
}
@Override
public void onStop() {
super.onStop();
// Remove post value event listener
if (mPostListener != null) {
mPostReference.removeEventListener(mPostListener);
}
// Clean up comments listener
mAdapter.cleanup();
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.button_post_comment) {
postComment();
}
}
private void postComment() {
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
assert mUser != null;
final String uid = mUser.getUid();
final DatabaseReference commentDb = FirebaseDatabase.getInstance().getReference().child("Users").child(uid);
commentDb.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
User user = dataSnapshot.getValue(User.class);
String authorName = user.name;
String commentUserPic = user.ProfilePic;
// Create new comment object
String commentText = mCommentField.getText().toString();
HashMap < String, Object > dateCreated; {
//Otherwise make a new object set to ServerValue.TIMESTAMP
dateCreated = new HashMap < String, Object > ();
dateCreated.put("timeStamp", ServerValue.TIMESTAMP);
}
HashMap < String, Boolean > commenter_id; {
commenter_id = new HashMap < String, Boolean > ();
commenter_id.put(getUid(), true);
}
Comment comment = new Comment(uid, authorName, commentText, commentUserPic, dateCreated, commenter_id);
// Push the comment, it will appear in the list
mCommentsReference.push().setValue(comment);
// Clear the field
mCommentField.setText(null);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
private static class CommentViewHolder extends RecyclerView.ViewHolder {
public CommentViewHolder(View itemView) {
super(itemView);
authorView = (TextView) itemView.findViewById(R.id.comment_author);
bodyView = (TextView) itemView.findViewById(R.id.comment_body);
postingTime = (TextView) itemView.findViewById(R.id.comment_post_time);
rm_comment = (Button) itemView.findViewById(R.id.remove_comment);
}
public void setImage(String images) {
this.imageDp = images;
userPic = (ImageView) itemView.findViewById(R.id.comment_photo);
Picasso.with(context).load(imageDp).into(userPic);
}
void bindToPost(Comment comment, View.OnClickListener starClickListener) {
authorView.setText(comment.author);
bodyView.setText(comment.text);
setImage(comment.commentPic);
setViewValue(comment.getTimestampCreatedLong());
rm_comment.setOnClickListener(starClickListener);
}
}
private class CommentAdepter extends FirebaseRecyclerAdapter < Comment, CommentViewHolder > {
private Context mContext;
private List < String > mCommentIds = new ArrayList < > ();
private List < Comment > mComments = new ArrayList < > ();
private String mkey;
CommentAdepter(Class < Comment > CommentClass, Class < CommentViewHolder > viewHolderClass, int modelLayout, DatabaseReference ref, final Context context) {
super(CommentClass, modelLayout, viewHolderClass, mCommentsReference);
mContext = context;
// Create child event listener
// [START child_event_listener_recycler]
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
Comment comment = dataSnapshot.getValue(Comment.class);
// mkey = dataSnapshot.getKey();
// [START_EXCLUDE]
// Update RecyclerView
mCommentIds.add(dataSnapshot.getKey());
mComments.add(comment);
notifyItemInserted(mComments.size() - 1);
// [END_EXCLUDE]
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
Comment newComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int commentIndex = mCommentIds.indexOf(commentKey);
if (commentIndex > -1) {
// Replace with the new data
mComments.set(commentIndex, newComment);
// Update the RecyclerView
notifyItemChanged(commentIndex);
} else {
Log.w(TAG, "onChildChanged:unknown_child:" + commentKey);
}
// [END_EXCLUDE]
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String commentKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int commentIndex = mCommentIds.indexOf(commentKey);
if (commentIndex > -1) {
// Remove data from the list
mCommentIds.remove(commentIndex);
mComments.remove(commentIndex);
// Update the RecyclerView
notifyItemRemoved(commentIndex);
} else {
Log.w(TAG, "onChildRemoved:unknown_child:" + commentKey);
}
// [END_EXCLUDE]
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
Comment movedComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("PostDetailActivity", "postComments:onCancelled", databaseError.toException());
Toast.makeText(mContext, "Failed to load comments.",
Toast.LENGTH_SHORT).show();
}
};
ref.addChildEventListener(childEventListener);
// [END child_event_listener_recycler]
// Store reference to listener so it can be removed on app stop
}
@Override
public int getItemCount() {
return mComments.size();
}
@Override
protected void populateViewHolder(final CommentViewHolder viewHolder, final Comment model, final int position) {
final DatabaseReference commentRef = getRef(position);
final String commentKey = commentRef.getKey();
if (model.commenter_id.containsKey(gUid())) {
viewHolder.rm_comment.setVisibility(View.VISIBLE);
}
viewHolder.bindToPost(model, new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext, "clicked " + commentKey, Toast.LENGTH_SHORT).show();
mCommentsReference.child(commentKey).removeValue();
}
});
}
}
private String gUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
}
如果你需要布局文件,请评论....
答案 0 :(得分:0)
我添加了删除FirebaseRecyclerAdapter中的项目的功能,并且通常遵循此帖子中的建议:
how to implement a SetOnItemClickListener FirebaseRecyclerViewAdapter
我使用了第一个解决方案,在populateViewHolder()中添加了一个ImageView.setOnClickListener()调用。它对我来说很好。
我不太清楚上面的#3问题是什么,但我遇到了一个问题,即数据在第一次被调用时没有填充。我在这篇文章中找到了我的解决方案,即确保将RecyclerView高度设置为match_parent:
FirebaseRecyclerAdapter - populateViewHolder is not populating the data for first time it runs?