Passing an Object from an Activity to a Fragment

前端 未结 8 2069
别那么骄傲
别那么骄傲 2020-11-27 10:55

I have an Activity which uses a Fragment. I simply want to pass an object from this Activity to the Fragment.

How

8条回答
  •  萌比男神i
    2020-11-27 11:41

    Passing arguments by bundle is restricted to some data types. But you can transfer any data to your fragment this way:

    In your fragment create a public method like this

    public void passData(Context context, List list, int pos) {
        mContext = context;
        mLexItemList = list;
        mIndex = pos;
    }
    

    and in your activity call passData() with all your needed data types after instantiating the fragment

            WebViewFragment myFragment = new WebViewFragment();
            myFragment.passData(getApplicationContext(), mLexItemList, index);
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.my_fragment_container, myFragment);
            ft.addToBackStack(null);
            ft.commit();
    

    Remark: My fragment extends "android.support.v4.app.Fragment", therefore I have to use "getSupportFragmentManager()". Of course, this principle will work also with a fragment class extending "Fragment", but then you have to use "getFragmentManager()".

提交回复
热议问题