title: Creating layout with code
body: <p>I have problem with creating layout with code. I'm just trying to add a button object on my linear layout but it doesn't create any button. </p>
  
  <p>Here's my onCreate method:</p>
  
  <pre><code>protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
      LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
  
      Button button = new Button(this);
      button.setText(R.string.click_me);
  
      layout.addView(button);
  
      if (savedInstanceState == null) {
          getFragmentManager().beginTransaction()
                  .add(R.id.container, new PlaceholderFragment())
                  .commit();
      }
  }
  </code></pre>
  
  <p>My fragment_main.xml:</p>
  
  <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_margin="10dp"
  android:id="@+id/layout"
  android:orientation="vertical" &gt;
  </code></pre>
  
  <p></p>
  
  <p><strong>***update 1***</strong></p>
  
  <p>So when adding objects on layout when you have a fragment xml it must be on the fragment class. Thanks to @Fllo for pointing that out. Haven't thought of that way. :( </p>
  
  <p>Here's my updated code in adding the button on PlaceHolderFragment class.</p>
  
  <pre><code>public static class PlaceholderFragment extends Fragment {
  
      public PlaceholderFragment() {
      }
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
              Bundle savedInstanceState) {
          View rootView = inflater.inflate(R.layout.fragment_main, container, false);
  
  
          LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.layout);
          Button button = new Button(getActivity());
          button.setText(R.string.click_me);
          layout.addView(button);
          return rootView;
      }
  }
  </code></pre>