Passing an Object from an Activity to a Fragment

前端 未结 8 2040
别那么骄傲
别那么骄傲 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: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

提交回复
热议问题