Groupie适配器中的SetOnItemClickListener不起作用

时间:2019-06-21 05:26:51

标签: android firebase android-recyclerview

我使用groupie lib来显示我从firebase数据库中获取的项目。但是当我想在Groupie适配器中执行setOnItemClickListener时,什么也没发生

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/users");
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            adapter = new GroupAdapter();

            for (DataSnapshot ds:dataSnapshot.getChildren()) {
                Userinfo user = ds.getValue(Userinfo.class);
                if(user !=null)
                adapter.add(new ContactItem(user));
            }

            newmessage_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            newmessage_recyclerview.addItemDecoration(new DividerItemDecoration(getApplicationContext(),DividerItemDecoration.VERTICAL));
            newmessage_recyclerview.setAdapter(adapter);

            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull Item item, @NonNull View view) {
                    Log.d("main", String.valueOf(item.getId()));
                }
            });

        }

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

        }
    });

1 个答案:

答案 0 :(得分:0)

您的适配器和列表视图应该在onDataChange() method外部进行初始化和分配,如您所见,每次Firebase数据库中的数据更改时,适配器都将被更改并且列表视图被重复设置,这是多余的。试试这个。

//set up adapter and listview one time only
adapter = new GroupAdapter();
newmessage_recyclerview.setLayoutManager(new 
LinearLayoutManager(getApplicationContext()));
newmessage_recyclerview.addItemDecoration(new 
DividerItemDecoration(getApplicationContext(),DividerItemDecoration.VERTICAL));
newmessage_recyclerview.setAdapter(adapter);

adapter.setOnItemClickListener(new OnItemClickListener() {
     @Override
     public void onItemClick(@NonNull Item item, @NonNull View view) {
          Log.d("main", String.valueOf(item.getId()));
     }
});

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/users");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

          for (DataSnapshot ds:dataSnapshot.getChildren()) {
               Userinfo user = ds.getValue(Userinfo.class);
               if(user !=null)
               adapter.add(new ContactItem(user));
               adapter.notifyDataSetChanged();
          }
      }

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

      }
 });