findViewById usage in View
<p>I'm struggling with a problem for a few days already and couldn't find solution to my problem so far.
I have two classes:
- StartActivity extends Activity
- TimeGraphView extends SurfaceView</p>

<p>What I want to achieve is to add dynamically buttons from within TimeGraphView to another view (LinearLayout).
To do so wanted to get that LinearLayout inside TimeGraphView with findViewById() but it returns null, and it should because I call it in TimeGraphView not in root element where I used setContentView();</p>

<p>So my question is how can I add button dynamically from custom view level to another view.</p>

<p>And my code:</p>

<pre><code>public class StartActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.time_graph);

        LinearLayout layout = (LinearLayout) this.findViewById(R.id.TimeGraphLayout);
        //here I can add button but it's not what I want
    }
}
</code></pre>

<p>and ...</p>

<pre><code>public class TimeGraphView extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    public TimeGraphView(Context context) {
        super(context);
    }

    public TimeGraphView(Context context, AttributeSet set) {
        super(context, set);
    }

    public TimeGraphView(Context context, AttributeSet set, int arg) {
        super(context, set, arg);
    }

    public void run() {
        while (run) {
            if (something) {
                LinearLayout layout = (LinearLayout) findViewById(R.id.TimeGraphLayout);
                if (layout != null) {
                    Button button = new Button(context);
                    button.setText(text);
                    layout.addView(button);
                } else {
                    Log.e("TimeGraphView", "TimeGraphLayout is null");
                    //and "layout" is always null and that's the problem ;(
                }
            }
        }
    }
}
</code></pre>

<p>... and my XML</p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TimeGraphRootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" &gt;

    &lt;HorizontalScrollViewa
        android:id="@+id/TimeGraphPanel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" &gt;

        &lt;LinearLayout
            android:id="@+id/TimeGraphLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" /&gt;
    &lt;/HorizontalScrollView&gt;

    &lt;my.package.TimeGraphView
        android:id="@+id/TimeGraphChart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" /&gt;

&lt;/LinearLayout&gt;
</code></pre>
