The following is running on an Android 1.6 so I'm using the compatibility package for fragments. In the following TestFragment
is a static nested class:
public class FragmentTestActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public static class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView result = new TextView(getActivity());
result.setText("Hello TestFragment");
return result;
}
}
}
The main.xml file:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<fragment class="com.test.FragmentTestActivity$TestFragment"
android:id="@+id/test"
android:layout_width="fill_parent" android:layout_height="fill_parent" />
</FrameLayout>
The strange thing is that the container parameter in onCreateView
is null
.
Now, if I add the fragment programatically like so(just change the onCreate
method of the Activity) the container is no longer null. Why?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment frag = new TestFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
}
The documentation mentions that it can be null:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
[...]
container: If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view.
To be clear: you shouldn't do anything like container.addView(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With