Build a UI in XML with Code
Description
You can build layouts in XML and then use code to populate the dynamic data.
Example
Creating a User Interface in XML with IDs
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- NAME CONTAINER -->/*from ww w. ja va2s .co m*/
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
<TextView
android:id="@+id/nameValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<!-- ADDRESS CONTAINER -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/app_name" />
<TextView
android:id="@+id/addrValue"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
The actual strings for these TextViews will come from our strings.xml file in the /res/values folder. The following code shows what our strings.xml file might look like.
<?xml version="1.0" encoding="utf-8"?>
<resources>/*from w w w.j a v a2 s . c o m*/
<string name="app_name">java2s.com</string>
<string name="hello_world">java2s.com</string>
<string name="action_settings">Settings</string>
</resources>
Referring to Controls in Resources at Runtime
/*ww w .j a va 2 s. co m*/
package com.java2s.app;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView nameValue = (TextView)findViewById(R.id.nameValue);
nameValue.setText("Main");
TextView addrValue = (TextView)findViewById(R.id.addrValue);
addrValue.setText("Street");
}
}