如何使用以编程方式创建的内容视图向活动添加片段
我想将一个片段添加到以编程方式实现其布局的Activity。我查看了Fragment文档,但没有很多示例描述我需要的内容。这是我尝试编写的代码类型:
public class DebugExampleTwo extends Activity { private ExampleTwoFragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout frame = new FrameLayout(this); if (savedInstanceState == null) { mFragment = new ExampleTwoFragment(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(frame.getId(), mFragment).commit(); } setContentView(frame); }}
...
public class ExampleTwoFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button button = new Button(getActivity()); button.setText("Hello There"); return button; }}
此代码编译但在开始时崩溃,可能是因为我FragmentTransaction.add()
的错误。这样做的正确方法是什么?
繁星点点滴滴
ibeautiful
相关分类