title: How to load programmatically a layout XML file in Android?
body: <p>I have made a layout (say <strong>my_layout.xml</strong>) which includes programmatically two other XML layout files, say <strong>some_layout.xml</strong> and <strong>another_layout.xml</strong>. <strong>my_layout.xml</strong> is drawn using <code>setContentView(R.layout.my_layout)</code>.</p>
  
  <p>Now I have a checkbox with ID <code>some_checkbox</code>, which is defined inside <strong>some_layout.xml</strong>, and I want to give the checkbox an <code>OnCheckedChangeListener</code> using <code>setOnCheckedChangeListener()</code>, just like this:</p>
  
  <pre><code>CheckBox cb = (CheckBox) findViewById(R.id.some_checkbox);
  cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      ...
  });
  </code></pre>
  
  <p>But now a <code>NullPointerException</code> is thrown, because <code>cb</code> is <code>null</code>. I guess that's because the layout containing <code>some_checkbox</code> (which is <strong>some_layout</strong>) is not loaded using <code>setContentView(R.layout.some_layout)</code>.</p>
  
  <ul>
  <li>Question 1: Why? Why returns finding <code>R.id.some_checkbox</code> <code>null</code>? <strong>some_layout</strong> really <em>is</em> visible.</li>
  <li>Question 2: How do I 'load' <strong>some_layout</strong> so I can capture <code>some_layout</code> into a variable, like I tried in the code snippet above?</li>
  </ul>
  
  <h2>UPDATE</h2>
  
  <p>I've finally solved it, using the following, suggested by <a href="https://stackoverflow.com/users/1627730/stealthjong">stealthjong</a>:</p>
  
  <blockquote>
    <p>One solution could be initialising the <code>checkedChangeListener</code>, adding a listener to your expandable listview, and when a child of the expandable listview is opened, checking if your <code>Checkbox</code> is one of the inflated children, and adding the <code>checkedchangeListener</code> if so.</p>
  </blockquote>
  
  <p>I've created a method called <code>setCheckedChangeListenerToElement(int resourceId, OnCheckedChangeListener listener)</code>, which saves the given resourceId (which is the ID of the element where to attach a listener to), and the given listener. Once the inflater calls the method <code>getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)</code>, the View can be retrieved. Then, on that View, <code>findViewById(int resourceId)</code> can be called, where <code>resourceId</code> is the ID of the checkbox.</p>