如何在片段中实现 UserAdapter 中的 holder.itemView.setOnClickListener?

How do I implement the holder.itemView.setOnClickListener from the UserAdapter in a fragment?

对于标题,我深表歉意,我不确定如何正确表达我的问题。

我有一个 UserAdapter、一个 Chatlist 和一个 Searchfragment 以及 user_item。问题是,三个点击侦听器 "Follow"、"Go to user's profile" 和 "Go to chatActivity" 在两个片段上都可用。

我想要 "Go to user's profile" 点击侦听器仅在 Searchfragment 中起作用,但在 Chatlistfragment 中不起作用,并且还要隐藏 Chatlistfragment 上的 "follow/following" 按钮。现在他们正在处理这两个片段。

我将不胜感激任何帮助!

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ImageViewHolder> {

private Context mContext;
private List<User> mUsers;
private boolean isFragment;

private FirebaseUser firebaseUser;

String theLastMessage;

public UserAdapter(Context context, List<User> users, boolean isFragment) {
    mContext = context;
    mUsers = users;
    this.isFragment = isFragment;
}

@NonNull
@Override
public UserAdapter.ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
    return new UserAdapter.ImageViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final UserAdapter.ImageViewHolder holder, final int position) {

    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

    final User user = mUsers.get(position);
    holder.btn_follow.setVisibility(View.VISIBLE);
    isFollowing(user.getId(), holder.btn_follow);

    holder.username.setText(user.getUsername());
    holder.fullname.setText(user.getFullname());
    Glide.with(mContext).load(user.getImage()).into(holder.image_profile);

    // Go to clicked user's profile
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isFragment) {
                SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
                editor.putString("profileid", user.getId());
                editor.apply();

                ((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new ProfileFragment()).commit();
            } else {
                Intent intent = new Intent(mContext, MainActivity.class);
                intent.putExtra("publisherid", user.getId());
                mContext.startActivity(intent);
            }
        }
    });

    // Start chatActivity with clicked user
    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Intent intent = new Intent(mContext, MessageActivity.class);
            intent.putExtra("userid", user.getId());
            mContext.startActivity(intent);

            return true;
        }
    });

    // Click handler: User can un / follow by clicking on the button
    holder.btn_follow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (holder.btn_follow.getText().toString().equals("follow")) {
                FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
                        .child("following").child(user.getId()).setValue(true);
                FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
                        .child("followers").child(firebaseUser.getUid()).setValue(true);

                addNotification(user.getId());
            } else {
                FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
                        .child("following").child(user.getId()).removeValue();
                FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
                        .child("followers").child(firebaseUser.getUid()).removeValue();
            }
        }

    });
}

// ViewHolder holding data of user
public class ImageViewHolder extends RecyclerView.ViewHolder {

    public TextView username, fullname, last_message;
    public CircleImageView image_profile;
    public Button btn_follow;

    public ImageViewHolder(View itemView) {
        super(itemView);

        username = itemView.findViewById(R.id.username);
        fullname = itemView.findViewById(R.id.fullname);
        image_profile = itemView.findViewById(R.id.image_profile);
        btn_follow = itemView.findViewById(R.id.follow_btn);
        last_message = itemView.findViewById(R.id.last_msg);
    }
}

我的 SearchFragment

public class SearchFragment extends Fragment {

    private RecyclerView recyclerView;
    private UserAdapter userAdapter;
    private List<User> userList;

    EditText search_bar;

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

        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        search_bar = view.findViewById(R.id.search_bar);

        userList = new ArrayList<>();
        userAdapter = new UserAdapter(getContext(), userList, true);
        recyclerView.setAdapter(userAdapter);

        readUsers();
        search_bar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                searchUsers(charSequence.toString().toLowerCase());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        return view;
    }

    private void searchUsers(String s){
        Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
                .startAt(s)
                .endAt(s+"\uf8ff");

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                userList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    User user = snapshot.getValue(User.class);
                        userList.add(user);
                }

                userAdapter.notifyDataSetChanged();
            }

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

            }
        });
    }

    private void readUsers() {

        final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (search_bar.getText().toString().equals("")) {
                    userList.clear();
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        User user = snapshot.getValue(User.class);

                        userList.add(user);

                    }

                    userAdapter.notifyDataSetChanged();
                }
            }

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

            }
        });
    }
}

我的聊天列表片段

public class ChatListFragment extends Fragment {

    private RecyclerView recyclerView;

    private UserAdapter userAdapter;
    private List<User> mUsers;
    FirebaseUser fuser;
    DatabaseReference reference;
    private List<Chatlist> usersList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_chat_list, container, false);

        // Init
        recyclerView = view.findViewById(R.id.chatList_recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        fuser = FirebaseAuth.getInstance().getCurrentUser();

        usersList = new ArrayList<>();

        reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser.getUid());
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                usersList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Chatlist chatlist = snapshot.getValue(Chatlist.class);
                    usersList.add(chatlist);
                }

                chatList();
            }

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

            }
        });

        return view;
    }

    private void chatList() {
        mUsers = new ArrayList<>();
        reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mUsers.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapshot.getValue(User.class);
                    for (Chatlist chatlist : usersList) {
                        if (user.getId().equals(chatlist.getId())) {
                            mUsers.add(user);
                        }
                    }
                }
                userAdapter = new UserAdapter(getContext(), mUsers, true);
                recyclerView.setAdapter(userAdapter);
            }

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

            }
        });
    }
}

我的User_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <!-- Profile Picture -->
    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/image_profile"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/profile" />

    <!-- Layout: Username, fullname, last message -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:layout_toEndOf="@+id/image_profile"
        android:orientation="vertical">

        <TextView
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:text="Benutzername"
            android:textColor="@color/colorProfileFollowPostText"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/fullname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:text="Name"
            android:textColor="@color/colorBlack" />

        <TextView
            android:id="@+id/last_msg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:maxLines="1"
            android:layout_marginEnd="10dp"
            android:text="Last message" />


    </LinearLayout>

    <!-- Button: Follow -->
    <Button
        android:id="@+id/follow_btn"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="10dp"
        android:background="@drawable/followbutton"
        android:padding="5dp"
        android:text="Folgen"
        android:textColor="@color/colorProfileFollowPostText"
        android:visibility="gone" />

</RelativeLayout>

通常在这种情况下,只需在适配器的构造函数中添加一个布尔值即可。 假设您的 isFragment 布尔值用于此目的。因此,如果 isFragment 为真,则将按钮可见性设置为 GONE,并且在单击 "Go to user's profile" 按钮时只需执行以下操作:

if (isFragment)
    return

希望对你有所帮助。