如何在recyclerview适配器的片段之间传递数据

时间:2017-10-12 05:31:22

标签: android android-fragments android-recyclerview

我有两个fragments,第一个片段有recyclerview adapter我想将适配器位置传递给clicking recycler view上的另一个片段..

来自recyclerview adapter

片段1 代码:

holder.address.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.i("Position of items...///", String.valueOf(position));
                            //For sending data between fragments

                            Bundle bundle = new Bundle();
                            bundle.putInt("Position", position);
                            StoreDetails storeDetails = new StoreDetails();
                            storeDetails.setArguments(bundle);
                            getActivity().getSupportFragmentManager()
                                    .beginTransaction()
                                    .replace(R.id.content_frame, new StoreDetails())
                                    .commit();

                        }
                    });

片段2代码:

Bundle b = getArguments();
    if(b != null)
    {
        b.getInt("Position");
    }
    else
    {
        Toast.makeText(getActivity(), "Oops sorry..!!", Toast.LENGTH_SHORT).show();
    }

2 个答案:

答案 0 :(得分:4)

  

您要在Bundle StoreDetails中添加Fragment,并且您正在传递StoreDetails Fragment的新对象

     

您需要传递StoreDetails Fragment中添加Bundle的相同对象,因此请将其更改为以下代码

使用此

Bundle bundle = new Bundle();
bundle.putInt("Position", position);
StoreDetails storeDetails = new StoreDetails();
storeDetails.setArguments(bundle);
getActivity().getSupportFragmentManager()
              .beginTransaction()
              .replace(R.id.content_frame,  storeDetails)
              .commit();

而不是

getActivity().getSupportFragmentManager()
             .beginTransaction()
             .replace(R.id.content_frame,new StoreDetails())
             .commit();

答案 1 :(得分:0)

试试这样:

    private Bundle bundle;

@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
     super.onActivityCreated(savedInstanceState);
     this.bundle = getArguments();
     if (bundle != null) {
         bundle.getInt("Position");
     } else {
         Toast.makeText(getActivity(), "Oops sorry..!!", Toast.LENGTH_SHORT).show();
             }
    }