Я хочу добавить фрагмент к Activity, который программно реализует его макет. Я просмотрел документацию по фрагментам, но там не так много примеров, описывающих то, что мне нужно. Вот тип кода, который я пытался написать:
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 ()
неверен. Как правильно это сделать?