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

时间:2019-07-17 14:12:28

标签: java android android-fragments recycler-adapter android-studio-3.0

我很抱歉标题,我不确定如何正确表达我的问题。

我有一个UserAdapter,一个聊天列表,一个Searchfragment和user_item。问题是,两个片段上都有三个“单击”侦听器“关注”,“转到用户的个人资料”和“转到chatActivity”。

我希望“转到用户的个人资料”单击侦听器仅在Searchfragment中起作用,而不在Chatlistfragment中起作用,并且还隐藏Chatlistfragment上的“关注/关注”按钮。现在,他们可以同时处理两个片段。

我将不胜感激!

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) {

            }
        });
    }
}

我的ChatlistFragment

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>

1 个答案:

答案 0 :(得分:0)

通常,在这种情况下,只需在适配器的构造函数中使用布尔值即可。 假设您的isFragment布尔值用于此目的。因此,如果isFragment为true,则只需将按钮的可见性设置为GONE,然后单击“转到用户的个人资料”按钮即可:

if (isFragment)
    return

希望对您有帮助。