Let us start with a LinearLayout. How would we declare it in an XML?
<?xml version="1.0" encoding="utf-8"?>
This just contains a TextView embedded in a LinearLayout. A very trivial example. But serves the purpose intended. Let me show how almost every single element here corresponds to a class or a method call in the class. So the equivalent code in the onCreate(…) method of an activity would be like this:
super.onCreate(savedInstanceState);Like this any layout view can be created. But from this small example you can notice two outstanding things – very tedious to code for every attribute of the view. And any simple change in the view, you need to change the code, compile, deploy and only then you see the effect of the change – unlike in a layout editor.
lLayout = new LinearLayout(this);
//-1(LayoutParams.MATCH_PARENT) is fill_parent or match_parent since API level 8
//-2(LayoutParams.WRAP_CONTENT) is wrap_content
tView = new TextView(this);
tView.setText("Hello, This is a view created programmatically! " +
"You CANNOT change me that easily :-)");
You can download the sample code here.