RecyclerView将值传递给片段

时间:2016-10-13 04:31:49

标签: android-fragments android-recyclerview

我应该如何对此进行编码以将我的RecyclerView数据传递给片段,以及我应该在片段中放入什么代码。这段代码适用于活动,我见过解决方案,但我不能让它为我工作。此代码来自recyclerview的适配器

    public MyHolder(View itemView) {
        super(itemView);
        textNotifTitle= (TextView) itemView.findViewById(R.id.textNotifTitle);
        textNotifMessage = (TextView) itemView.findViewById(R.id.textNotifMessage);
        TextDate = (TextView) itemView.findViewById(R.id.textDate);
        itemView.setOnClickListener(this);
        }
        @Override
        public void onClick(View view) {
            //Open the new activity (THIS WORKS)
            Intent intent = new Intent(context, NotifActivity.class);
            Bundle bundle = new Bundle();
            int position = getAdapterPosition();
            Toast.makeText(context,"this is the position"+position, Toast.LENGTH_SHORT);

            bundle.putSerializable("DATA", data.get(getAdapterPosition()));


            intent.putExtras(bundle);
            context.startActivity(intent);
            }

1 个答案:

答案 0 :(得分:1)

您好,您必须更改代码:

@Override
        public void onClick(View view) {
            //Open the new activity (THIS WORKS)
            Intent intent = new Intent(context, NotifActivity.class);
            Bundle bundle = new Bundle();
            int position = getAdapterPosition();
            Toast.makeText(context,"this is the position"+position, Toast.LENGTH_SHORT);

            bundle.putSerializable("DATA", data.get(getAdapterPosition()));


            intent.putExtras(bundle);
            context.startActivity(intent);
            }

    @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            int position = getAdapterPosition();
            Toast.makeText(context,"this is the position"+position, Toast.LENGTH_SHORT);

            bundle.putSerializable("DATA", data.get(getAdapterPosition()));
YourFragmentName f = new YourFragmentName();
f.setArguments(bundle);
   getActivity().getSupportFragmentManager().beginTransaction()
                .replace(R.id.your_container_frame_layout,
                f).commit();
            }

将任何bundle传递给你必须putExtras函数的活动,但在Fragment中你必须设置setArguments函数。

您可以通过以下代码获取Fragment中的包:

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       Bundle b = getArguments();
        if (b != null) {
            //todo your code
        }

    }