以下是在 Android 1.6 上运行的,所以我将兼容性包用于片段。下面TestFragment
是一个静态嵌套类:
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;
}
}
}
main.xml 文件:
<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>
奇怪的是里面的容器参数onCreateView
是null
.
现在,如果我像这样以编程方式添加片段(只需更改onCreate
Activity 的方法),则容器不再为空。为什么?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment frag = new TestFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
}