在 recyclerview 适配器中显示自定义弹出窗口 class - Android Java

Show customize pop up in recycler view adapter class - Android Java

我有一个片段 class,其中包含编辑文本、按钮和 recycler view。我的回收站视图使用 card view 的 xml 布局。我的卡片视图包含文本视图和一个按钮(?)以在单击后显示弹出窗口。

我尝试像往常一样在我的片段 class 中添加弹出代码,但它指出我的片段无法访问回收站的视图卡视图布局。所以我尝试将它添加到我的适配器 class 中,但我陷入了 getActivty() 无法识别的困境。
这是我在 on click

中的 view holder 方法中添加的内容
                    btnHelp.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Popup_FreedomWall popup_freedomWall = new Popup_FreedomWall();
                            Bundle args = new Bundle();
                            System.out.println("=================TVFWID==========================");
                            System.out.println(tvFwId.getText().toString());
                            System.out.println("=====================TVFWID======================");
                            //data to get for report - uid(reported,get reported),freedom wall id
                            args.putString("user", mod_freedomWall.uid_report);
                            args.putString("reportedPost", tvFwId.getText().toString());
                            popup_freedomWall.setArguments(args);

                            popup_freedomWall.show();
                            popup_freedomWall.show(getActivity().getSupportFragmentManager(), "My Fragment");
                        }
                    });
    ```
<br/>


`Mod_FreedomWall.java` 我的片段
public class Mod_FreedomWall extends Fragment {
    RecyclerView recyclerView;
    Mod_FreedomWall_UserAdapter myAdapter;
    FragmentManager fragmentManager;
    ArrayList<Mod_FreedomWall_User> user;
  @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.mod_freedomwall, container, false);
        recyclerView = (RecyclerView) v.findViewById(R.id.freedomWallPost);

        return v;

    }

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recyclerView = (RecyclerView) view.findViewById(R.id.freedomWallPost);
        recyclerView.setHasFixedSize(true);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, true);
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);


        btnPost.setOnClickListener(new View.OnClickListener() {
            final Date c = Calendar.getInstance().getTime();
            final SimpleDateFormat df = new SimpleDateFormat("MM-dd-yy", Locale.getDefault());
            final String formattedDate = df.format(c);
            final Date currentTime = Calendar.getInstance().getTime();
            final DateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
            final String dateString = dateFormat.format(new Date());

            @Override
            public void onClick(View v) {
                String message = etPost.getText().toString();
                createPost(message, user_name, dateString, formattedDate, level);
                myAdapter.notifyDataSetChanged();
                etPost.setText("");
            }
        });

        user = new ArrayList<Mod_FreedomWall_User>();
        retrievePost();

        myAdapter = new Mod_FreedomWall_UserAdapter(this, user);
        myAdapter.setListener(new Mod_FreedomWall_UserAdapter.MyListener() {
            @Override
            public void onItemClicked(String uid, String fwid) {
                Popup_FreedomWall popup_freedomWall = new Popup_FreedomWall();
                Bundle args = new Bundle();

  //just to see if I'm getting data              
System.out.println("=================TVFW==========================");
                System.out.println(fwid);
            System.out.println("=====================TVFW======================");

                args.putString("user",uid);
                args.putString("reportedPost", fwid);
                popup_freedomWall.setArguments(args);
                popup_freedomWall.show(getActivity().getSupportFragmentManager(), "pop_upFreedomWall");
            }
        });
        recyclerView.setAdapter(myAdapter);
    }


我的适配器

public class Mod_FreedomWall_UserAdapter extends RecyclerView.Adapter<Mod_FreedomWall_UserAdapter.ViewHolder> {
    Mod_FreedomWall mod_freedomWall = new Mod_FreedomWall();
    private ArrayList<Mod_FreedomWall_User> user;
    String freeId,reporterId;

    public  Mod_FreedomWall_UserAdapter(Mod_FreedomWall context, ArrayList<Mod_FreedomWall_User> list){
        user = list;
    }
    
public  class ViewHolder extends RecyclerView.ViewHolder{
        ImageView ivUserProfile;
        TextView tv_message,tv_username,tv_date,tvTime,tvFwId;
        Button btnHelp;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            btnHelp = (Button) itemView.findViewById(R.id.btnHelp);
            ivUserProfile = (ImageView) itemView.findViewById(R.id.ivUserProfile);
            tv_message = (TextView) itemView.findViewById(R.id.tv_message);
            tv_username = (TextView) itemView.findViewById(R.id.tv_username);
            tv_date = (TextView) itemView.findViewById(R.id.tv_date);
            tvTime = (TextView) itemView.findViewById(R.id.tvTime);
            tvFwId = (TextView) itemView.findViewById(R.id.tvFwId);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnHelp.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            System.out.println("=================TVFWID==========================");
                            System.out.println(tvFwId.getText().toString());
                            System.out.println("=====================TVFWID======================");
                            freeId = tvFwId.getText().toString();
                            reporterId = mod_freedomWall.uid_report;
                        }
                    });
                }
            });
        }
    }


    @NonNull
    @Override
    public Mod_FreedomWall_UserAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.mod_freedomwall_post,viewGroup,false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull Mod_FreedomWall_UserAdapter.ViewHolder viewHolder, int position) {
        viewHolder.itemView.setTag(user.get(position));

        viewHolder.tvFwId.setVisibility(View.INVISIBLE);
        viewHolder.tv_message.setText(user.get(position).getMessage());
        viewHolder.tv_username.setText(user.get(position).getUsername());
        viewHolder.tv_date.setText(user.get(position).getDate());
        viewHolder.tvTime.setText(user.get(position).getTime());
        viewHolder.tvFwId.setText(user.get(position).getFreedomWallId());
        viewHolder.ivUserProfile.setImageResource(R.drawable.ic_username_white);

    }
    @Override
    public int getItemCount() {
        return user.size();
    }
    public interface MyListener {
        void onItemClicked(String uid,String fwid); 
    }

    MyListener mListener;


    public void setListener(MyListener listener) {
        mListener = listener;
    }
}



先感谢您!

据我了解,您有两种可能的方法来解决这个问题。

  1. 在您的适配器的构造函数中发送一个上下文,并将您需要“getActivity()”的部分替换为您通过的上下文(obv 通过您的适配器中的一个变量)。
  2. 使用接口方法。 我从不喜欢上下文风格,所以我会给你一个接口方法的例子。

在您的适配器中:

public abstract class YourAdapter extends ...<> {

    public interface MyListener {
        void onItemClicked(String someData); //can change this variable to whatever is needed, if any.
    }

    MyListener mListener;
    ...

然后让按钮的onClickListener调用你刚刚创建的Interface函数,而不是直接尝试做一个popup:

    btnHelp.setOnClickListener(v -> onItemClicked("this is my data i pass through");

然后向您的适配器添加一个函数以设置侦听器(或将其作为参数添加到构造函数中,无论您想要什么):

public void setListener(MyListener listener) {
        mListener = listener;
    }

并在您的 Fragment 中实现侦听器:

adapter.setListener(new YourAdapter.MyListener() {
        @Override
        public void onItemClicked(String myData) {
            //create your popup and simply call getActivity() since this is inside the Fragment
        }
    });

--- 你的片段 ---

public class Mod_FreedomWall extends Fragment {

    RecyclerView recyclerView;
    RecyclerView.Adapter myAdapter; //<-- 1 *remove*
    RecyclerView.LayoutManager layoutManager; // obsolete, can be deleted. You make a local variable later on.
    Mod_FreedomWall_UserAdapter adapter; // <-- 2 *rename to myAdapter*
  @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.mod_freedomwall, container, false);
        recyclerView = (RecyclerView) v.findViewById(R.id.freedomWallPost);

        return v;

    }

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recyclerView = (RecyclerView) view.findViewById(R.id.freedomWallPost);
        recyclerView.setHasFixedSize(true);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, true);
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);

// You call a function of `adapter` here, but adapter hasn't been 
// properly initialised yet, it's null so far, so that won't go well. 
// *rename adapter to myAdapter and move this part down*
adapter.setListener(new Mod_FreedomWall_UserAdapter.MyListener() {
            @Override
            public void onItemClicked(String uid, String fwid) {
                Popup_FreedomWall popup_freedomWall = new Popup_FreedomWall();
                Bundle args = new Bundle();
                //data to get for report - uid(reported,get reported),freedom wall id
                args.putString("user",uid);
                args.putString("reportedPost", fwid);
                popup_freedomWall.setArguments(args);
                popup_freedomWall.show(getActivity().getSupportFragmentManager(), "My Fragment");
            }
        });

        btnPost.setOnClickListener(new View.OnClickListener() {
            final Date c = Calendar.getInstance().getTime();
            final SimpleDateFormat df = new SimpleDateFormat("MM-dd-yy", Locale.getDefault());
            final String formattedDate = df.format(c);
            final Date currentTime = Calendar.getInstance().getTime();
            final DateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
            final String dateString = dateFormat.format(new Date());

            @Override
            public void onClick(View v) {
                String message = etPost.getText().toString();
                createPost(message, user_name, dateString, formattedDate, level);
                myAdapter.notifyDataSetChanged();
                etPost.setText("");
            }
        });

        user = new ArrayList<Mod_FreedomWall_User>();
        retrievePost();

        //Here you initialise your adapter
        myAdapter = new Mod_FreedomWall_UserAdapter(this, user);
        //you can move your `myAdapter.setListener` to this spot.
        recyclerView.setAdapter(myAdapter);
    }

好吧,您声明了两个适配器,但实际上只使用了一个。好像有点乱。

待办事项; 废弃其中一个适配器(1 号)。那么最简单的方法就是把2号处的adapter重命名为myAdapter,同时把adapter.setListener处的adapter改成myAdapter.setListener(....

然后将 myAdapater.setListener(... 移动到 myAdapter = new Mod_FreedomWall_UserAdapter(this, user); 下面的位置,因为那是您实际初始化适配器的地方。在那之前,您无法安全地调用适配器的功能。