Passing an Object from an Activity to a Fragment

前端 未结 8 1911
别那么骄傲
别那么骄傲 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条回答
  • 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<LexItem> 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()".

    0 讨论(0)
  • 2020-11-27 11:43

    You should create a method within your fragment that accepts the type of object you wish to pass into it. In this case i named it "setObject" (creative huh? :) ) That method can then perform whatever action you need with that object.

    MyFragment fragment;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    
            if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
                fragment = new MyFragment();
                getSupportFragmentManager().beginTransaction().add(android.R.id.content, detailsFragment)
                        .commit();
            } else {
               fragment = (MyFragment) getSupportFragmentManager().findFragmentById(
                        android.R.id.content);
            }
    
    
            fragment.setObject(yourObject); //create a method like this in your class "MyFragment"
    }
    

    Note that i'm using the support library and calls to getSupportFragmentManager() might be just getFragmentManager() for you depending on what you're working with

    0 讨论(0)
提交回复
热议问题