Android fragment declared in layout, how to set arguments?

I have a snippet that uses the getArguments () method in onCreateView to get some input.

I use this snippet with ViewPager and it works great.

The problem starts when I try to reuse this fragment in another action, which shows only this fragment. I wanted to add a fragment to the activitie 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" /> 

Question: how to pass a package to the fragment declared in the layout?

+4
android android-fragments
Jan 28 '14 at 10:29
source share
2 answers

A better way would be to change the value in FrameLayout and put the fragment in the 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 that this will somehow reduce performance?

+11
Jan 29 '14 at 21:03
source share

If you stick to the fragment declaration in your layout, you can use this check in 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 calling startActivity ()

+1
Jan 06 '15 at
source share



All Articles