使用FirebaseRecyclerAdapter在RecyclerView的结束/开始添加项目

时间:2017-04-12 03:06:09

标签: android firebase firebase-realtime-database android-recyclerview firebaseui

cmdr= (RecyclerView) findViewById(R.id.cmdr);
        mLayoutManager = new LinearLayoutManager(InterR.this);
        mLayoutManager.setReverseLayout(true);
        mLayoutManager.setStackFromEnd(true);         

Query q= FirebaseDatabase.getInstance().getReference().child("com").orderByChild("id").equalTo(idrc.getText().toString());

                mAdapter4 = new FirebaseRecyclerAdapter<Cmd,mViewHolder>(Cmd.class,R.layout.item_cmd_r,mViewHolder.class,
                        q) {


                    @Override
                    protected void populateViewHolder(mViewHolder viewHolder, Cmd model, int position) {

                        if(this.getRef(position).getKey()!=null)
                        {viewHolder.idc.setText(this.getRef(position).getKey());}


                        if(model.getAddress()!=null)
                        {viewHolder.adc.setText(model.getAdresse());}

                    }

                };
            mAdapter4.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver()
            {


                @Override
                public void onItemRangeInserted(int positionStart, int ItemCount){
                    super.onItemRangeInserted(positionStart,ItemCount);
                    int roomCount = mAdapter4.getItemCount();
                    int lastVisiblePosition = mLayoutManager.findLastCompletelyVisibleItemPosition();
                    if (lastVisiblePosition == -1 || (positionStart >= (roomCount -1) && lastVisiblePosition == (positionStart -1))){
                        cmdr.scrollToPosition(positionStart);
                    }

                }
            });

            cmdr.setLayoutManager(mLayoutManager);
            cmdr.setAdapter(mAdapter4);

我尝试使用FirebaseRecyclerAdapter检索到的数据填充RecyclerView,它正在运行,但问题是无论何时添加某个项目,而不是显示在列表末尾或顶部, item插入与数据库中相同的位置

1 个答案:

答案 0 :(得分:0)

在FirebaseRecyclerAdapter声明中,重写getItem()函数。

    @Override
public User getItem(int position) {
        return super.getItem(getItemCount() - 1 - position);
}

归功于https://github.com/firebase/FirebaseUI-Android/issues/310#issuecomment-247816246