Question

I am having an experiment to create a layout programmatically in MainActivity. In the MainActivity, there is also a SurfaceView element. I am aware LayoutInflater can be used to inflate an XML to a View object but can't figure out how it is done when everything is in code.

Code below gives a RuntimeException and NullPointerException error

public class MainActivity extends Activity implements Runnable {

    private SurfaceView p_view;
    private boolean p_running;
    private Thread p_thread;
    private RelativeLayout p_rLayout;
    private int p_picNum;
    private Bitmap p_picImage;
    private ImageView p_imgV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //RelativeLayout p_rLayout with an ImageView component
        p_rLayout = new RelativeLayout (this);
        p_rLayout.setLayoutParams(new RelativeLayout.LayoutParams (
            LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        p_imgV = new ImageView(this);
        p_picNum = getResources().getIdentifier(
            "square", "drawable", getPackageName());
        p_picImage = BitmapFactory.decodeResource (getResources(), p_picNum);
        p_imgV.setImageBitmap(p_picImage);
        p_rLayout.addView(p_imgV, new RelativeLayout.LayoutParams (
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        //A SurfaceView-element for drawing a circle
        p_view = new SurfaceView(this);                

        //Inflate p_rLayout to the SurfaceView-element p_view
        ViewGroup viewGroup = (ViewGroup)this.getLayoutInflater().inflate(
            null, p_rLayout);
        viewGroup.addView(p_view);
        setContentView(viewGroup);

        p_thread = new Thread(this);
        p_thread.start();
        p_running = true;
    }

    @Override
    public void run() {
        while(p_running) {
            if(p_view.getHolder().getSurface().isValid()) {
                p_canvas = p_view.getHolder().lockCanvas();
                //Draw a circle
                p_view.getHolder().unlockCanvasAndPost(p_canvas);
            }
        }
    }
}
Was it helpful?

Solution

You need layout inflater only when converting XML layouts to view hierarchies. When you create the view hierarchy in code, you don't need a layout inflater.

Replace this code:

ViewGroup viewGroup = (ViewGroup)this.getLayoutInflater().inflate(
        null, p_rLayout);
viewGroup.addView(p_view);
setContentView(viewGroup);

with something like

p_rLayout.addView(p_view);
setContentView(p_rLayout);

to add the SurfaceView to the RelativeLayout (you probably want to adjust the layout params) and then add the RelativeLayout as your content view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top