title: How do I add a Fragment to an Activity with a programmatically created content view
body: <p>I want to add a Fragment to an Activity that implements its layout programmatically. I looked over the Fragment documentation but there aren't many examples describing what I need. Here is the type of code I tried to write:</p>
  
  <pre><code>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);
      }
  }
  </code></pre>
  
  <p>...</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>This code compiles but crashes at start, probably because my <code>FragmentTransaction.add()</code> is incorrect. What is the correct way to do this?</p>