Android Fragment declared in layout, how to set arguments?

The best way would be to change the to FrameLayout and put the fragment in code.

public void onCreate(...) {

    ScheduleDayFragment fragment = new ScheduleDayFragment();
    fragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction()
                .add(R.id.main_view, fragment).commit();
    ...
}

Here is the layout file

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

Are you worried this is going to reduce performance somehow?


i know its too late answer, but i think someone need that :)

just in activity override onAttachFragment()

@Override
public void onAttachFragment(@NonNull Fragment fragment)
{
    super.onAttachFragment(fragment);

    if (fragment.getId() == R.id.frgBlank)
    {
        Bundle b = new Bundle();
        b.putString("msg", "Message");

        fragment.setArguments(b);
    }
}

and in fragment onCreateView method

Bundle b = getArguments();
if (b != null)
{
    Toast.makeText(requireContext(), b.getString("msg"), Toast.LENGTH_SHORT).show();
}

just like that, hope to help someone :)


If you are stick with the fragment declaration within your layout, you can use this check within your Fragment.OnCreateView()

    if (savedInstanceState != null) {
        // value can be restored after Fragment is restored
        value = savedInstanceState.getInt("myValueTag", -1);

    } else if (getArguments() != null) {
        // value is set by Fragment arguments
        value = getArguments().getInt("myValueTag", -1);

    } else if (getActivity() != null && getActivity().getIntent() != null) {
        // value is read from activity intent
        value = getActivity().getIntent().getIntExtra("myValueTag", -1);
    }

finally just add your value information to the intent created for startActivity() call