Search code examples
androidandroid-layoutandroid-4.0-ice-cream-sandwichandroid-4.4-kitkatandroid-relativelayout

Android - FrameLayout with a custom view requiring a constructor


What I am attempting to do is take a custom view (which is a constructor & onDraw method) and a set of controls in a RelativeLayout and display them together with-in a FrameLayout. My code currently gets to adding the overlay and crashes with a Null Pointer Execption but if I directly add the overlay and cut out the FrameLayout & custom view it works.

FrameLayout layout = new FrameLayout(this);
SampleView sv = new SampleView(this, objectA, objectB, ObjectC), RESULTS);
RelativeLayout overlay = (RelativeLayout) findViewById(R.layout.analysis_overlay);

layout.addView(sv);
layout.addView(overlay);

setContentView(layout);

I assume there is a better way to do this and I've seen examples of a FrameLayout existing in xml but I didn't see anyway of setting the constructor via that method... So is there a better way of doing this that still allows custom view to have a constructor or did I mess somthing up with my current code?


Solution

  • You are attempting to find an id of a layout resource. Instead, inflate your relative layout (the layout resource) and then add it.

    FrameLayout layout = new FrameLayout(this);
    SampleView sv = new SampleView(this, objectA, objectB, ObjectC), RESULTS);
    RelativeLayout overlay = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.analysis_overlay, layout, false);
    
    
    layout.addView(sv);
    layout.addView(overlay);
    
    setContentView(layout);