简体   繁体   English

如何使用CardView Item在`RecyclerView.Adapter'中单击侦听器

[英]How to add an Item Click Listener in `RecyclerView.Adapter' using CardView Item

How can I add an Item Click Listener for my `RecyclerView.Adapter' when the user clicks on the Card View item, Data sent to the PostContent Fragment? 当用户单击Card View项目时,如何为“ RecyclerView.Adapter”添加项目Click侦听器,即数据发送到PostContent Fragment?

Also, is it possible to send the data from this adapter to the new fragment using intent? 另外,是否可以使用意图将数据从此适配器发送到新片段?

Please note my code: 请注意我的代码:

public class PostDataAdapter extends RecyclerView.Adapter<PostDataAdapter.MyViewHolder> {

    private List<PostData> PostDataList ;
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView vPostContent, vPostDate, vPostAuthor, vPostTitr,VPostLikes,VPostViews;
        public ImageView vPostPhoto;

        public MyViewHolder(View v) {
            super(v);

            vPostContent = v.findViewById(R.id.PostContentTv);
            vPostDate = v.findViewById(R.id.PostDateTv);
            vPostAuthor = v.findViewById(R.id.PostAuthorTv);
            vPostTitr = v.findViewById(R.id.PostTitrTv);
            vPostPhoto = v.findViewById(R.id.PostPhoto);
            VPostLikes=v.findViewById(R.id.PostLikeTv);
            VPostViews=v.findViewById(R.id.PostViewTv);


        }

    }

    public PostDataAdapter(List<PostData> postDataList) {
        PostDataList = postDataList;
    }

    @Override
    public PostDataAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_posts, parent, false);
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.vPostDate.setText(PostDataList.get(position).getPostDate());
        holder.vPostTitr.setText(PostDataList.get(position).getPostTitr());
        holder.vPostContent.setText(PostDataList.get(position).getPostContent());
        holder.vPostAuthor.setText(PostDataList.get(position).getPostAuthor());
        holder.VPostViews.setText(PostDataList.get(position).getPostViews());
        holder.VPostLikes.setText(PostDataList.get(position).getPostLikes());
        new DownloadImageTask(holder.vPostPhoto).execute(PostDataList.get(position).getImgpost());

    }

    @Override
    public int getItemCount() {
        return PostDataList.size();
    }
}

Yu cand send data from Adapter to a Fragment with Intent: Yu can有意向地将数据从适配器发送到片段:

Fragment fragment = new tasks();
FragmentManager fragmentManager = context.getSupportFragmentManager(); // this is the context of the Activity
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("name", "Osmar Cancino"); //key and value
//set Fragmentclass Arguments
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Although my suggestion is to manage the flow of screens from the parent activity, and manage the data through a Callback, even with a custom Interface 尽管我的建议是管理父活动的屏幕流,并通过回调(即使使用自定义界面)来管理数据

There are two ways you can do this. 有两种方法可以执行此操作。

  1. Write recyclerview.onitem touchlistener(...). 编写recyclerview.onitem touchlistener(...)。 Then consume that event in your fragment. 然后在片段中消耗该事件。 As you will get item position inside touchlistener callback, you can take out data from your list directly from the list you passed to your adapter (Assuming you have list reference outside in your fragment.) 当您在touchlistener回调中获得项目位置时,可以直接从传递给适配器的列表中从列表中取出数据(假设片段中有列表引用)。

  2. Oobserver pattern. 观察者模式。 Define a functional interface (one callback method with required parameters of the data you want to pass) implement inside your fragment. 在片段内定义一个功能接口(一种具有要传递的数据的必需参数的回调方法)实现。 Send its reference with the constructor of adapter. 使用适配器的构造函数发送其参考。 Then Store reference in a interface type variable inside adapter. 然后将引用存储在适配器内部的接口类型变量中。 Write click listener on card. 在卡上写入点击监听器。 And on the card click, invoke method using interface type variable. 然后在卡上单击,使用接口类型变量调用方法。

Intents can be used to send data to new activities but not fragments You'd have to use the Fragment Manager and attach a bundle to it to send data. 意图可以用于将数据发送到新活动,但不能用于片段。您必须使用片段管理器并将附加束捆绑到其中以发送数据。 You can refer to the documentation here on how to do so: 您可以在此处参考文档以了解如何操作:

https://developer.android.com/training/basics/fragments/communicating#Deliver https://developer.android.com/training/basics/fragments/communicating#Deliver

To handle click on cards, you can create a listener when you create PostDataAdapter. 要处理卡上的单击,可以在创建PostDataAdapter时创建一个侦听器。 Refer to the following link for a simple example: 请参考以下链接以获取简单示例:

https://stackoverflow.com/a/40584425/4260853 https://stackoverflow.com/a/40584425/4260853

To add a ItemCLickListener for RecyclerView , you need to implement a custom Interface which the Fragment will implement. 要为RecyclerView添加ItemCLickListener ,您需要实现一个Fragment将实现的自定义Interface When the list item is clicked, then the callback function of the interface is called. 单击列表项后,将调用接口的回调函数。

CustomItemClickListener.java : CustomItemClickListener.java

public CustomItemClickListener {
    void onItemClick(Object data);
}

Just add these to the PostDataAdapter: 只需将这些添加到PostDataAdapter:

PostDataAdapter.java : PostDataAdapter.java

private CustomItemClickListner clickListener;
public PostDataAdapter(CustomItemClickListner listener, List<PostData> postDataList) {
    PostDataList = postDataList;
    clickListener = listener
}


@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    holder.vPostCardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Modify the parameters of the function according to what you want to send to the fragment 
            // As soon as this is called, the `onItemClick` function implemented in the Fragment gets called.
            clickListener.onItemClick(Object data);
        }
    });
}

Fragment.java : Fragment.java

CustomFragment extends Fragment implements CustomItemClickListener {
    public CustomFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view;
        PostDataAdapter adapter = new PostDataAdapter(this, new ArrayList<PostData>)
        return view;
    }

    @Override
    public void onItemClick(Object data) {
        // Handle the data sent by the adapter on item click
    }
}

for adding click item for a Cardview, you can find the Cardview in MyViewHolder class by id and in onBindViewHolder set a click listerner for it like the following 要添加Cardview的单击项,您可以通过id在MyViewHolder类中找到Cardview,并在onBindViewHolder中为其设置点击列表查看器,如下所示

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

holder.vPostCardView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //write your codes here

    }
});
}

if you have an intent that you want to send it's data to a fragment, you can get the intent data and send them with bundle to your fragment. 如果您有想要将其数据发送到片段的意图,则可以获取该意图数据并将其与捆绑包一起发送到片段。 for example do something like the following. 例如,执行以下操作。

Bundle bundle = new Bundle();
bundle.putString("your_key",intent.getStringExtra("your_item_key_in_intent"));

and after that send bundle to your fragment with 然后将捆绑包发送到您的片段

fragment.setArguments(bundle);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM