Как правильно обрабатывать позиции RecyclerView? - PullRequest
0 голосов
/ 03 июля 2019

Я использую обзор переработчика, и внутри его адаптера у меня есть другой просмотр переработчика.

Как предотвратить изменение элемента и обновление элемента при обновлении элемента.Это создает визуальные глюки и неправильное позиционирование элементов

Я пытался прочитать непосредственно из базы данных ссылку на текущую позицию держателя.

Результат: https://media.giphy.com/media/j6TpXZRE6e44cMZVIP/giphy.gif

public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder>{
private Context mContext;

    private List<Comments> mComments;
    private List<Replies> allReplies;

    public CommentsAdapter(Context mContext, List<Comments> mComments, List<Replies> allReplies )
    {
        this.mContext = mContext;
        this.mComments = mComments;
        this.allReplies = allReplies;
    }

    @NonNull
    @Override
    public CommentsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.all_comments_layout, viewGroup, false);
        return new CommentsAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
    {
        final Comments comments = mComments.get(position);


        holder.like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    CommentUps.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            {
if (dataSnapshot.child(PostKey).child(com_uid).hasChild(currentUserID)) {
                                    CommentUps.child(PostKey).child(com_uid).child(currentUserID).removeValue();
                                  CommentsRef.child(PostKey).child(com_uid).child("likes").setValue(comments.getLikes() - 1);


                                } else {
                                    CommentUps.child(PostKey).child(com_uid).child(currentUserID).setValue(true);
                                    CommentsRef.child(PostKey).child(com_uid).child("likes").setValue(comments.getLikes() + 1);



                                }
}
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });
                }

            }
        });



        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Replies");

        //reference.orderByChild("pLikes")

        reference.orderByChild(com_uid).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                holder.repliesList.clear();
                for (DataSnapshot snapshot : dataSnapshot.child(PostKey).child(com_uid).getChildren())
                {

                    Replies replies = snapshot.getValue(Replies.class);
                    //final String com = comment.toString();
                    // Log.d(new String("Comments"), com);
                    //for (String id : followingList)

                        if (replies.getComment_uid().equals(com_uid))
                        {

                        holder.repliesList.add(replies);
                        }
                }
                holder.repliesAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }


    @Override
    public int getItemCount() {
        return mComments.size();
    }


public class ViewHolder extends RecyclerView.ViewHolder {

        ImageButton like
        List<Replies> repliesList;
        RepliesAdapter repliesAdapter;


        public ViewHolder(View itemView) {
            super(itemView);

            like = itemView.findViewById(R.id.comment_like_button);
            repliesRecycler = itemView.findViewById(R.id.all_replies_recycler);

            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
            repliesRecycler.setLayoutManager(linearLayoutManager);
            repliesRecycler.setHasFixedSize(true);
            repliesList = new ArrayList<>();

            repliesAdapter = new RepliesAdapter(mContext, repliesList);
            repliesRecycler.setAdapter(repliesAdapter);
            repliesAdapter.notifyDataSetChanged();


        }


        // Second Method - Same Result
        private void displayReplies(final String com_uid ,final String PostKey, final boolean locked) {

            DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Replies");

            reference.child(PostKey).child(com_uid).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    repliesList.clear();

                    if (dataSnapshot.exists()) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                                final Replies replies = snapshot.getValue(Replies.class);

                                if (replies.getComment_uid().equals(com_uid)) {
                                    repliesList.add(replies);
                                    repliesAdapter.notifyDataSetChanged();
                                }
                        }
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
        }
}

Адаптер моих ответов:

public class RepliesAdapter extends RecyclerView.Adapter<RepliesAdapter.ViewHolder>
{
    public Context mContext;
    public List<Replies> mReplies;

    public RepliesAdapter(Context mContext, List<Replies> mReplies)
    {
        this.mContext = mContext;
        this.mReplies = mReplies;


    }

    @NonNull
    @Override
    public RepliesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.all_replies_layout, viewGroup, false);

        mAuth = FirebaseAuth.getInstance();
        return new RepliesAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
    {
final Replies replies = mReplies.get(position);

        holder.myUserName.setText(replies.getUsername());
        holder.myComment.setText(replies.getReply());
        holder.myTime.setText(replies.getTime());
    }


    @Override
    public int getItemCount() {

        return mReplies.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView myUserName, myComment,myTime;


        public ViewHolder(View itemView) {
            super(itemView);

            myUserName = itemView.findViewById(R.id.reply_username);
            myComment = itemView.findViewById(R.id.reply_text);
            myTime = itemView.findViewById(R.id.reply_time);

        }


    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...