Fragment.onCreateView has null container

孤街浪徒 提交于 2020-01-30 04:17:10

问题


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();
}

回答1:


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(...).



来源:https://stackoverflow.com/questions/10116143/fragment-oncreateview-has-null-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!