kmalmur
kmalmur

Reputation: 2839

Android Fragment declared in layout, how to set arguments?

I've got a fragment that uses getArguments() method in onCreateView, to get some input data.

I'm using this fragment with ViewPager and it works fine.

The problem starts when I try to reuse this fragment in a different activity, that shows this fragment only. I wanted to add the fragment to the activitie's layout:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment"
    android:name="com.example.ScheduleDayFragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

The question is: how to pass a Bundle to a fragment declared in layout?

Upvotes: 8

Views: 6825

Answers (3)

A S A D I
A S A D I

Reputation: 159

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 :)

Upvotes: 6

Mario
Mario

Reputation: 758

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

Upvotes: 2

Aswin Rajendiran
Aswin Rajendiran

Reputation: 3409

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?

Upvotes: 15

Related Questions