Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 616
kmalmur Avatar asked Jan 28 '14 10:01

kmalmur


1 Answers

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?

like image 77
Aswin Rajendiran Avatar answered Oct 15 '22 12:10

Aswin Rajendiran