如何在不重新填充整个列表的情况下使用新项更新我的firebase适配器

时间:2017-07-29 14:06:08

标签: android-studio firebase android-recyclerview infinite-scroll

我试图在我的firebase回收站视图中实现无休止的滚动。我将查询限制为5个项目,然后用户滚动到列表的末尾,查询被更新,限制增加了我的另一个5.但是适配器仅在我离开并返回活动时更新。我尝试过notifydatasetchange(),但这并不起作用。我试过了recyclerview.setadapter()。它有效,但它也重置了我的回收者视图的滚动位置。似乎没有其他工作。

@Override
public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState){
    View view=inflater.inflate(R.layout.card_view,container,false);

    mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
    mDatabaseUpvote= FirebaseDatabase.getInstance().getReference().child("Upvote");
    mAuth=FirebaseAuth.getInstance();
    recyclerView = (RecyclerView) view.findViewById(R.id.recycleview_new);
    recyclerView.setHasFixedSize(true);

    mLayoutManager=(new LinearLayoutManager(getActivity()));
    recyclerView.setLayoutManager(mLayoutManager);
    mDatabaseUpvote.keepSynced(true);
    mDatabase.keepSynced(true);


    query=mDatabase.limitToFirst(count);


    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            firstItem=mLayoutManager.findLastVisibleItemPosition();
            ItemCount=recyclerView.getChildCount();
            TotalItemCount=mLayoutManager.getItemCount();

            if (loading){
                if (TotalItemCount>prevTotal){
                    loading=false;
                    prevTotal=TotalItemCount;
                }
            }

            if (!loading && (TotalItemCount-firstItem) <= (firstItem+visthresh)){

                count=count+2;
                query=mDatabase.limitToFirst(count);




                Toast.makeText(getActivity(), "ThresholdReached", Toast.LENGTH_SHORT).show();

                loading=true;
            }
        }
    });





 firebaseRecyclerAdapter  = new FirebaseRecyclerAdapter<Cards, Postviewholder>(

            Cards.class,
            R.layout.cards,
            Postviewholder.class,
         query

    ) {
        @Override
        protected void populateViewHolder(final Postviewholder viewHolder, Cards model, final int position) {



            final String postKey=getRef(position).getKey();

            viewHolder.setUsername(model.getUsername());
            viewHolder.setImage(getActivity(),model.getImage());
            viewHolder.setimage_icon(getActivity(),model.getImageicon());
            viewHolder.setTitle(model.getTitle());
            viewHolder.setTextColor(model.getTextColor());
            viewHolder.setUpvote(postKey);



            viewHolder.post_Image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent2= new Intent(getActivity(),View_post.class);
                    intent2.putExtra("Userprofile",postKey);
                    startActivity(intent2);

                }
            });

            viewHolder.imageicon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent2= new Intent(getActivity(),UserActivity_2.class);
                    intent2.putExtra("Userprofile",postKey);
                    startActivity(intent2);


                }
            });





            viewHolder.upvote.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ProcessUpvote = true;



                    mDatabaseUpvote.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (ProcessUpvote) {
                                if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {

                                    mDatabaseUpvote.child(postKey).child(mAuth.getCurrentUser().getUid()).removeValue();
                                    ProcessUpvote = false;

                                } else {
                                    mDatabaseUpvote.child(postKey).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
                                    ProcessUpvote = false;
                                }

                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });


                }
            });
        }

    };
    recyclerView.setAdapter(firebaseRecyclerAdapter);



    if (sharedPreferences != null) {

        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(getActivity());

        Posit=(preferences.getInt(RV_POS_INDEX,0));
        mRvTopView=(preferences.getInt(RV_TOP_VIEW,0));
        Toast.makeText(getActivity(), "RestoreState", Toast.LENGTH_SHORT).show();
        firebaseRecyclerAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            public void onItemRangeInserted(int positionStart, int itemCount) {

                mLayoutManager.scrollToPositionWithOffset(Posit, mRvTopView);
            }
        });
    }



    return view;
}


@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    Posit = mLayoutManager.findFirstVisibleItemPosition();
    View startView = recyclerView.getChildAt(0);

    mRvTopView = (startView == null) ? 0 : (startView.getTop() - recyclerView.getPaddingTop());
    Toast.makeText(getActivity(), "SaveState", Toast.LENGTH_SHORT).show();

     sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());

    SharedPreferences.Editor editor=sharedPreferences.edit();
    editor.putInt(RV_POS_INDEX,Posit);
    editor.putInt(RV_TOP_VIEW,mRvTopView);
    editor.apply();


}





public  static class Postviewholder extends RecyclerView.ViewHolder {

    View mView;
    ImageView upvote;
    ImageView imageicon;
    ImageView post_Image;
    private DatabaseReference mDatabaseUpvote;

    private FirebaseAuth mAuth;


    public Postviewholder(View itemView) {
        super(itemView);
        mView = itemView;

        imageicon = (ImageView) mView.findViewById(R.id.Post_imiageicon);
        post_Image = (ImageView) mView.findViewById(R.id.CardImage);
        upvote = (ImageView) mView.findViewById(R.id.upvote);
        mDatabaseUpvote = FirebaseDatabase.getInstance().getReference().child("Upvote");
        mAuth = FirebaseAuth.getInstance();
    }

    public void setUpvote(final String postKey) {

        mDatabaseUpvote.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {


                    upvote.setImageResource(R.drawable.ic_thumb_up_black_24dp2);

                } else {
                    upvote.setImageResource(R.drawable.ic_thumb_up_black_24dp);
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


    }


    public void setImage(final Context ctx, final String image) {
        final ImageView imageView = (ImageView) mView.findViewById(R.id.CardImage);
        Glide.with(ctx)
                .load(image)
                .into(imageView);
    }


    public void setTitle(String title) {

        TextView cardtitle = (TextView) mView.findViewById(R.id.cardTitle);
        cardtitle.setText(title);


    }


    public void setUsername(String username) {
        TextView post_username = (TextView) mView.findViewById(R.id.post_username);
        post_username.setText(username);
    }

    public void setimage_icon(final Context ctx, final String imageicon) {
        final ImageView image_icon = (ImageView) mView.findViewById(R.id.Post_imiageicon);
        Glide.with(ctx)
                .load(imageicon)
                .into(image_icon);
    }

    public void setTextColor(int TextColor) {
        CardView cardView= (CardView)mView.findViewById(R.id.Cardview_card);
        TextView post_username = (TextView) mView.findViewById(R.id.post_username);
        TextView cardtitle = (TextView) mView.findViewById(R.id.cardTitle);
        int textcolr=getContrastColor(TextColor);
        int white=Color.WHITE;
        int resultColor =  blendARGB(TextColor,white,0.1f);
        cardView.setCardBackgroundColor(resultColor);
        cardtitle.setTextColor(textcolr);
        post_username.setTextColor(textcolr);
    }


}

}

0 个答案:

没有答案