如何从firebase中的孩子的参考中获取密钥

时间:2017-07-23 07:37:40

标签: java android firebase firebase-realtime-database

以下是我的Firebase架构:

Book {
    Book-1: {title, author}
    Book-2: {title, author}
    Book-3: {title, author}
    Book-4: {title, author}
}

我已将它们列在RecyclerView中并通过FirebaseRecyclerAdapter填充。下面给出了相同的代码:

final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Book");

    firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Book, BookListHolder>(
            Book.class,
            R.layout.simple_book_vertical_list,
            BookListHolder.class,
            ref) {
        @Override
        protected void populateViewHolder(BookListHolder viewHolder, Book model, int position) {
            viewHolder.setBookTitle(model.getTitle());
            viewHolder.setBookAuthor(model.getAuthor());
        }
    };

现在,点击视图后,我想显示点击的视图中的数据,即他们的标题和作者。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

设置点击监听器:

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String key = firebaseRecyclerAdapter.getRef(mRecycler.getChildLayoutPosition(v)).getKey();
                    // do your magic here
                }
            });

            return viewHolder;
        }