ViewPager2 adapter item layout flattened

302 Views Asked by At

I'm facing an issue with my viewpager2 adapter. The adapter contains a share button which starts an new activity with a create chooser Intent. The problem is if swipe down or press the android back button the current item layout is flattened or sometime it changes the current item to the next one. However if go through the sharing process completely the app works fine.

ViewPager2.JAVA*


public class StreamPostDetailAdapter extends RecyclerView.Adapter<StreamPostDetailAdapter.TestPagerViewHolder> {

    public Context mContext;
    public List<Post> mPost;
    private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    String mUid ;
    public IpagerAdapter mListener;
    private CommentAdapter commentAdapter;
    private List<Comment> commentList;

    public StreamPostDetailAdapter(Context mContext, List<Post> mPost, IpagerAdapter mListener) {
        this.mListener = mListener;
        this.mContext = mContext;
        this.mPost = mPost;
        mUid = firebaseUser.getUid();
    }

    @NonNull
    @Override
    public TestPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_post_swipe_item, parent, false);

        return new TestPagerViewHolder(view,mListener);
    }

    @Override
    public void onBindViewHolder(@NonNull TestPagerViewHolder holder, int position) {
        Post post = mPost.get(holder.getBindingAdapterPosition());
        String post_publisher = post.getPublisher();
        String post_id = post.getPostid() ;
        String post_image = post.getPostimage() ;
        String post_timeStamp = post.getTimestamp();
        String tag_list = post.getTagList();
        String postTitle = post.getDescription();
        boolean personal = post.getPersonal_tattoo();
        commentList = new ArrayList<>();
        commentAdapter = new CommentAdapter(mContext,commentList);
        GlideApp.with(mContext).load(post_image)
                .placeholder(R.mipmap.loading_img_placeholder)
                .into(holder.image_post);
       
        holder.title.setText(post.getDescription());

        if (post.getTagList().equals("")) {
            holder.tagList.setVisibility(View.GONE);
        } else {
            holder.tagList.setVisibility(View.VISIBLE);
            holder.tagList.setText(post.getTagList());
        }

        holder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.bsCommentsController(post_id, holder.commentRv);
                BottomSheetBehavior.from(holder.bsComments).setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        });
        holder.like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.like.getTag().equals("like")) {
                    FirebaseDatabase.getInstance().getReference().child("Likes")
                            .child(post_id)
                            .child(mUid).setValue(true);
                } else {
                    FirebaseDatabase.getInstance().getReference().child("Likes")
                            .child(post_id)
                            .child(mUid).removeValue();
                }
            }
        });
        holder.image_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
                    editor.putString("id", post_publisher);
                    editor.apply();
                    Intent intent  = new Intent(mContext,HomeActivity.class);
                    intent.putExtra("origin","ViewPager");
                    mContext.startActivity(intent);
                    ((StreamPostDetailActivity)mContext).finish();
            }
        });
        holder.save.setOnClickListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View v) {
                     if (mContext instanceof SavedPostActivity) {
                        mListener.removePost(post_id,post_image,position);
                     }
                     if (holder.save.getTag().equals("save")) {
                         FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
                                 .child(post_id).setValue(true);
                     } else {
                         FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
                                 .child(post_id).removeValue();
                     }

                 }
             });

        holder.share_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BitmapDrawable drawable = (BitmapDrawable)holder.image_post.getDrawable();
                Bitmap bitmap = drawable.getBitmap();
                String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, UUID.randomUUID().toString() + ".jpeg", "drawing");
                Uri uri = Uri.parse(path);
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_STREAM,uri);
                intent.putExtra(Intent.EXTRA_TEXT, "Playstore Link : put app link in store ");
                mContext.startActivity(Intent.createChooser(intent,"Share2"));
            }
        });

        if (mContext instanceof SearchTattooDetailsActivity) {
            holder.btn_post_options.setVisibility(View.GONE);
        }else {
            holder.btn_post_options.setVisibility(View.VISIBLE);
            holder.btn_post_options.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showMoreOptions(holder.btn_post_options, post_publisher, mUid, post_id, post_image, position, postTitle
                            , tag_list, personal);
                }
            });
        }


        // Add a new comment
        holder.sendComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!holder.comment_bar_edt.getText().toString().equals("")){
                    mListener.addComment(post_id, holder.comment_bar_edt.getText().toString());
                    holder.comment_bar_edt.setText("");
                    holder.comment_bar_edt.clearFocus();
                }
            }
        });
        holder.commentRv.setHasFixedSize(true);
        holder.commentRv.setAdapter(commentAdapter);
    }

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

    private void showMoreOptions(ImageButton btn_post_options, String post_publisher, String mUid, String post_id, String post_image,int posItem, String postTitle, String tagList, boolean personal) {
        PopupMenu popupMenu = new PopupMenu(mContext,btn_post_options, Gravity.END);
        if (!post_publisher.equals(mUid)) {
            popupMenu.getMenu().add(Menu.NONE,0,0,"Report post");
        }
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int id = item.getItemId();
                if (id == 0){
                    Toast.makeText(mContext, "CreateReportPost/UserNewCategoryRequestEmail", Toast.LENGTH_SHORT).show();
                } else if (id == 1) {
                    //not working
                    Intent intentEdit = new Intent(mContext, EditPostActivity.class);
                    intentEdit.putExtra("title",postTitle);
                    intentEdit.putExtra("imageUrl", post_image);
                    intentEdit.putExtra("tagList", tagList );
                    intentEdit.putExtra("personal", personal );
                    intentEdit.putExtra("postId", post_id);
                    intentEdit.putExtra("posEditedPost", posItem);
                    ((Activity)mContext).finish();
                    mContext.startActivity(intentEdit);

                }
                return false;
            }
        });
        popupMenu.show();
    }

    //View Holder Class
    public static class TestPagerViewHolder extends RecyclerView.ViewHolder {
        public ImageView image_profile, image_post, like, comment, save,share_post;
        public TextView username, likes, comments, title, time,tagList;
        public ImageButton btn_post_options;
        public IpagerAdapter mListener;
        //Comments Bottom sheet
        EditText comment_bar_edt;
        public RecyclerView commentRv ;
        ImageView sendComment,userImgComment;
        public ConstraintLayout bsComments;
        public LinearLayoutManager layoutManager;

        public TestPagerViewHolder(@NonNull View itemView, IpagerAdapter mListener) {
            super(itemView);
            this.mListener = mListener;
            image_post = itemView.findViewById(R.id.post_image);
            image_profile = itemView.findViewById(R.id.image_profile);
            like = itemView.findViewById(R.id.like_ic);
            share_post= itemView.findViewById(R.id.share_post);
            comment = itemView.findViewById(R.id.comment_ic);
            save = itemView.findViewById(R.id.save);
            username = itemView.findViewById(R.id.username);
            likes = itemView.findViewById(R.id.likes);
            comments = itemView.findViewById(R.id.comments);
            tagList = itemView.findViewById(R.id.tagList);
            title = itemView.findViewById(R.id.title);
            time = itemView.findViewById(R.id.time);
            btn_post_options = itemView.findViewById(R.id.post_options);
            bsComments= itemView.findViewById(R.id.bsComments);
            comment_bar_edt = itemView.findViewById(R.id.comment_bar_edt);
            sendComment = itemView.findViewById(R.id.sendComment);
            commentRv = itemView.findViewById(R.id.comments_rv);

            BottomSheetBehavior.from(bsComments).setState(BottomSheetBehavior.STATE_HIDDEN);

        }
    }

    public interface IpagerAdapter {
        void removePost(String post_id, String post_image, int position);
        void bsCommentsController(String post_id, RecyclerView commentRecyclerView);
        void addComment(String post_id,String comment_txt);
    }

   
   
    public void removeItem(int position) {
        if (position > -1 && position < mPost.size()) {
            mPost.remove(position);
            notifyDataSetChanged();
            notifyItemRemoved(position);
        }
    }

}
1

There are 1 best solutions below

0
MonkeyNation On

@Francis, Since It has been a while, I just remember that I've made changes in how I handled the BottomSheet which was containing the Comments RecyclerView. I extracted it from the StreamPostDetailAdapter (ViewPager2) and moved it to the corresponding activity. Therefore I have only one BottomSheet for all viewpager2 items. Then recyclerView data (comments fetch from firebase) is updated using interface listener methods to populate each items. You will find the code of the ViewPager2 below:

public class StreamPostDetailAdapter extends RecyclerView.Adapter<StreamPostDetailAdapter.TestPagerViewHolder> {

public Context mContext;
public List<Post> mPost;
private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String mUid ;
public IpagerAdapter mListener;
private CommentAdapter commentAdapter;
private List<Comment> commentList;

public StreamPostDetailAdapter(Context mContext, List<Post> mPost, IpagerAdapter mListener) {
    this.mListener = mListener;
    this.mContext = mContext;
    this.mPost = mPost;
    mUid = firebaseUser.getUid();
}

@NonNull
@Override
public TestPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_post_swipe_item, parent, false);

    return new TestPagerViewHolder(view,mListener);
}

@Override
public void onBindViewHolder(@NonNull TestPagerViewHolder holder, int position) {
    Post post = mPost.get(holder.getBindingAdapterPosition());
    String post_publisher = post.getPublisher();
    String post_id = post.getPostid() ;
    String post_image = post.getPostimage() ;
    String post_timeStamp = post.getTimestamp();
    String tag_list = post.getTagList();
    String postTitle = post.getDescription();
    boolean personal = post.getPersonal_tattoo();
    GlideApp.with(mContext).load(post_image)
            .placeholder(R.mipmap.loading_img_placeholder)
            .into(holder.image_post);

    holder.title.setText(post.getDescription());

    if (post.getTagList().equals("")) {
        holder.tagList.setVisibility(View.GONE);
    } else {
        holder.tagList.setVisibility(View.VISIBLE);
        holder.tagList.setText(post.getTagList());
    }


    publisherInfo(holder.image_profile, holder.username, post_publisher);
    asLiked(post_id, holder.like);
    nLikes(holder.likes, post_id);
    //getComments(post_id, holder.comments);
    isSaved(post_id, holder.save);
    getTimeAgo(holder.time, post_timeStamp);



    holder.comment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mListener.openBsComment();
        }
    });
    holder.like.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (holder.like.getTag().equals("like")) {
                FirebaseDatabase.getInstance().getReference().child("Likes")
                        .child(post_id)
                        .child(mUid).setValue(true);
            } else {
                FirebaseDatabase.getInstance().getReference().child("Likes")
                        .child(post_id)
                        .child(mUid).removeValue();
            }
        }
    });
    holder.image_profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
            editor.putString("id", post_publisher);
            editor.apply();
            Intent intent  = new Intent(mContext,HomeActivity.class);
            intent.putExtra("origin","ViewPager");
            mContext.startActivity(intent);
            ((StreamPostDetailActivity)mContext).finish();
        }
    });
    holder.save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mContext instanceof SavedPostActivity) {
                mListener.removePost(post_id,post_image,position);
            }
            if (holder.save.getTag().equals("save")) {
                FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
                        .child(post_id).setValue(true);
            } else {
                FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
                        .child(post_id).removeValue();
            }

        }
    });

    holder.share_post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BitmapDrawable drawable = (BitmapDrawable)holder.image_post.getDrawable();
            Bitmap bitmap = drawable.getBitmap();
            mListener.sharePost(bitmap);
        }
    });

    if (mContext instanceof TaggedTattooDetailsActivity) {
        holder.btn_post_options.setVisibility(View.GONE);
    }else {
        holder.btn_post_options.setVisibility(View.VISIBLE);
        holder.btn_post_options.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMoreOptions(holder.btn_post_options, post_publisher, mUid, post_id, post_image, position, postTitle
                        , tag_list, personal);
            }
        });
    }


    // Add a new comment

}

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

private void showMoreOptions(ImageButton btn_post_options, String post_publisher, String mUid, String post_id, String post_image,int posItem, String postTitle, String tagList, boolean personal) {
    PopupMenu popupMenu = new PopupMenu(mContext,btn_post_options, Gravity.END);
    if (!post_publisher.equals(mUid)) {
        popupMenu.getMenu().add(Menu.NONE,0,0,"Report post");
    }
    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            int id = item.getItemId();
            if (id == 0){
                Toast.makeText(mContext, "CreateReportPost/UserNewCategoryRequestEmail", Toast.LENGTH_SHORT).show();
            } else if (id == 1) {
                //not working
                Intent intentEdit = new Intent(mContext, EditPostActivity.class);
                intentEdit.putExtra("title",postTitle);
                intentEdit.putExtra("imageUrl", post_image);
                intentEdit.putExtra("tagList", tagList );
                intentEdit.putExtra("personal", personal );
                intentEdit.putExtra("postId", post_id);
                intentEdit.putExtra("posEditedPost", posItem);
                ((Activity)mContext).finish();
                mContext.startActivity(intentEdit);
            }
            return false;
        }
    });
    popupMenu.show();
}

//View Holder Class
public static class TestPagerViewHolder extends RecyclerView.ViewHolder {
    public ImageView image_profile, image_post, like, comment, save,share_post;
    public TextView username, likes, comments, title, time,tagList;
    public ImageButton btn_post_options;
    public IpagerAdapter mListener;
    //Comments Bottom sheet

    public LinearLayoutManager layoutManager;

    public TestPagerViewHolder(@NonNull View itemView, IpagerAdapter mListener) {
        super(itemView);
        this.mListener = mListener;
        image_post = itemView.findViewById(R.id.post_image);
        image_profile = itemView.findViewById(R.id.image_profile);
        like = itemView.findViewById(R.id.like_ic);
        share_post= itemView.findViewById(R.id.share_post);
        comment = itemView.findViewById(R.id.comment_ic);
        save = itemView.findViewById(R.id.save);
        username = itemView.findViewById(R.id.username);
        likes = itemView.findViewById(R.id.likes);
        comments = itemView.findViewById(R.id.comments);
        tagList = itemView.findViewById(R.id.tagList);
        title = itemView.findViewById(R.id.title);
        time = itemView.findViewById(R.id.time);
        btn_post_options = itemView.findViewById(R.id.post_options);


    }
}

public interface IpagerAdapter {
    void removePost(String post_id, String post_image, int position);
    void openBsComment();
    void sharePost(Bitmap postImage);
}

private void getComments(String postid, TextView comments) {
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(postid);
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.getChildrenCount() != 0) {
                comments.setText(" " + snapshot.getChildrenCount());
            } else {
                comments.setVisibility(View.GONE);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

private void getTimeAgo(TextView time, String stamp_post) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");;
    Log.i(TAG, "timestamp value in format date: "+ stamp_post);
    try {
        long timeStamp = sdf.parse(stamp_post).getTime();
        long now = System.currentTimeMillis();
        CharSequence ago = DateUtils.getRelativeTimeSpanString(timeStamp, now, DateUtils.MINUTE_IN_MILLIS);
        Log.i(TAG, "timestamp milli value is: " + timeStamp);
        time.setText(ago);
    } catch (ParseException e) {
        e.printStackTrace();
    }

}

private void asLiked(String postid, final ImageView imageView) {
    final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.child(firebaseUser.getUid()).exists()) {
                imageView.setImageResource(R.drawable.liked);
                imageView.setTag("liked");
            } else {
                imageView.setImageResource(R.drawable.ic_like);
                imageView.setTag("like");
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

private void nLikes(final TextView likes, String postid) {
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            likes.setText(" "+ snapshot.getChildrenCount());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

private void isSaved(String postid, final ImageView imageView) {
    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid());
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.child(postid).exists()) {
                imageView.setImageResource(R.drawable.ic_bookmark_colored);
                imageView.setTag("saved");
            } else {
                imageView.setImageResource(R.drawable.ic_save_post);
                imageView.setTag("save");
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

private void publisherInfo(ImageView image_profile, TextView username, String userid) {
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("App_users")
            .child(userid);

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            User user = snapshot.getValue(User.class);
            Glide.with(mContext.getApplicationContext()).load(user.getimageUrl()).into(image_profile);
            username.setText(user.getUsername());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

public void removeItem(int position) {
    if (position > -1 && position < mPost.size()) {
        mPost.remove(position);
        notifyDataSetChanged();
        notifyItemRemoved(position);
    }
}

}