将数据从活动传递到片段transaction.replace()

时间:2017-07-25 11:51:36

标签: java android android-fragments

将数据从活动传递到片段(片段重叠)时出现问题: 我需要传递带有包含复选框id的整数的arraylist来检查...

在传递数据之前: enter image description here

传递数据后: enter image description here

将数据从活动传递到片段的代码:

 Bundle bundle = new Bundle();
    bundle.putIntegerArrayList("oki", hm);
    System.out.println("PERO:" + bundle);

    MyListFragment myFragment = new MyListFragment();
    myFragment.setArguments(bundle);

   FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.container, myFragment);


    transaction.commit();

获取数据的代码:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();
        try {
        bundle = getArguments();

        System.out.println("BUNDLES:" + bundle);
        //if (bundle != null) {


                strtext = bundle.getIntegerArrayList("oki");
                System.out.println("AH:" + strtext);


        //}
        }catch(Exception e){

        }

2 个答案:

答案 0 :(得分:0)

MyListFragment

中的

private ArrayList mArrayList;

public void setArrayList(ArrayList arraylist)
{
    this.mArrayList = arraylist;
}

您可以随时随地访问mArrayList

然后做

    Bundle bundle = new Bundle();
    bundle.putIntegerArrayList("oki", hm);
    System.out.println("PERO:" + bundle);

    MyListFragment myFragment = new MyListFragment();
    myFragment.setArrayList(hm);


    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.container, myFragment);


    transaction.commit();

答案 1 :(得分:0)

    In your Activity

private List List = new ArrayList<>();

     FragmentName FragName = new FragmentName();
     Bundle bundle = new Bundle();                              
     bundle.putParcelable("key",List);
     FragName.setArguments(addEditBundle);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, FragName);

        transaction.commit();

In your Fragment 

private List List = new ArrayList<>();
    List = getArguments()。getParcelable(“Key”);