1

I need to pass data to a fragment, declared in activity layout before it is rendered:

<fragment android:name="com.app.fragments.MyFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myFragment" />

I tried to do it in Activity's onCreate but fragment is already rendered at that time.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Here fragment is already rendered
    mPosts = (MyFragment)getSupportFragmentManager().findFragmentById(R.id.myFragment);
    mPosts.setData(someData);
}

I've seen the way when fragment is created programmatically in activity onCreate and than added to a container. It's not a very bad solution. But... Is there anything simpler?

Andrei
  • 42,814
  • 35
  • 154
  • 218
  • 1
    You might want to take a look at [http://stackoverflow.com/questions/13034746/if-i-declare-a-fragment-in-an-xml-layout-how-do-i-pass-it-a-bundle](http://stackoverflow.com/questions/13034746/if-i-declare-a-fragment-in-an-xml-layout-how-do-i-pass-it-a-bundle) – Peter Chaula Nov 06 '16 at 04:50
  • @MikeM. yes, I thought about both ways and decided to go with what Peter suggested. Thanks for help guys – Andrei Nov 06 '16 at 05:23

1 Answers1

1

For XML layout there is one question over here: https://stackoverflow.com/a/23226281/842607

Even they has to say you cannot pass arguments, but you can use callbacks or custom attributes.

Else

Normally, we use Bundle in arguments in this way:

Fragment class

public class ShopProductListingFragment extends Fragment {

    private static final String TAG = ShopProductListingFragment.class.getSimpleName();

    public static final String KEY_CATEGORY = "category";
    public static final String KEY_URL_PARAMS = "url_params";
    public static final String KEY_URL = "url";

    public static ShopProductListingFragment getInstance(NewCategory category, @NonNull HashMap<String, String> urlParams) {
        Bundle bundle = new Bundle();
        if (null != category)
            bundle.putLong(KEY_CATEGORY, category.getCategory_id());
        bundle.putSerializable(KEY_URL_PARAMS, urlParams);

        ShopProductListingFragment fragment = new ShopProductListingFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public static ShopProductListingFragment getInstance(@NonNull String url) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_URL, url);

        ShopProductListingFragment fragment = new ShopProductListingFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public ShopProductListingFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initVals();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_shop_product_listing, container, false);
        ButterKnife.bind(this, rootView);
        initViews();
        return rootView;
    }

    private void initVals() {
        Bundle bundle = getArguments();

        if (null == bundle || Bundle.EMPTY == bundle)
            throw new NullPointerException("Invalid or null arguments passed to fragment ShopProductListingFragment");

        if (bundle.containsKey(KEY_CATEGORY))
            categoryId = bundle.getLong(KEY_CATEGORY);
        mCategory = StyFi.getInstance().getCategory(categoryId);
        if (bundle.containsKey(KEY_URL_PARAMS))
            urlParams = (HashMap<String, String>) bundle.getSerializable(KEY_URL_PARAMS);
        if (bundle.containsKey(KEY_URL))
            urlFilter = bundle.getString(KEY_URL);
    }

}

Layout file of Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

This is how it is instantiated in Activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        if (null == savedInstanceState) {
            ShopProductListingFragment fragment = ShopProductListingFragment.getInstance(category, getUrlParams(data));

            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, "SHOP");
            fragmentTransaction.commit();
        }
    }
Community
  • 1
  • 1
Jimit Patel
  • 4,265
  • 2
  • 34
  • 58