Creating Android UI Programmatically
Join the DZone community and get the full member experience.
Join For FreeLet us start with a LinearLayout. How would we declare it in an XML?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
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);
lLayout = new LinearLayout(this);
lLayout.setOrientation(LinearLayout.VERTICAL);
//-1(LayoutParams.MATCH_PARENT) is fill_parent or match_parent since API level 8
//-2(LayoutParams.WRAP_CONTENT) is wrap_content
lLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
tView = new TextView(this);
tView.setText("Hello, This is a view created programmatically! " +
"You CANNOT change me that easily :-)");
tView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
lLayout.addView(tView);
setContentView(lLayout);
You can download the sample code here.
Published at DZone with permission of Sai Geetha M N, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments