I’m trying to copy and then edit a layout view defined in an XML file.
//Create layout
LinearLayout layout = new LinearLayout(this);
//Add views
layout = (LinearLayout)findViewById(R.id.layout1);
//layout.addView(textView);
setContentView(layout);
This seems like it should work, but every time I run it, the app crashes when I call line
setContentView(layout);.
I’ve double checked the id’s and they are fine and they are both LinearLayouts.
Any idea what’s going wrong?
Quite simply you can’t call
findViewByIdbeforesetContentViewbecause there is no layout set to find a view in! What will happen probably isfindViewByIdwill returnnull, and then you attempt to set the content aslayout(which is null) thus getting an error there.Call
setContentViewwith your layout resource ID or actual view first, then find yourLinearLayoutwithfindViewById.