Build a UI Completely in Code
Description
The first example demonstrates how to build the UI entirely in code.
Example
Generate a project from Android Studio, cut and paste the following code to the
MainActivity.java
.
package com.java2s.app;
//from w w w.j av a2s .c o m
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout nameContainer = new LinearLayout(this);
LinearLayout addressContainer = new LinearLayout(this);
LinearLayout parentContainer = new LinearLayout(this);
nameContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
nameContainer.setOrientation(LinearLayout.HORIZONTAL);
TextView nameLbl = new TextView(this);
nameLbl.setText("Name: ");
TextView nameValue = new TextView(this);
nameValue.setText("Java2s.com");
nameContainer.addView(nameLbl);
nameContainer.addView(nameValue);
addressContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
addressContainer.setOrientation(LinearLayout.VERTICAL);
TextView addrLbl = new TextView(this);
addrLbl.setText("Address:");
TextView addrValue = new TextView(this);
addrValue.setText("Main Street");
addressContainer.addView(addrLbl);
addressContainer.addView(addrValue);
parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
parentContainer.setOrientation(LinearLayout.VERTICAL);
parentContainer.addView(nameContainer);
parentContainer.addView(addressContainer);
setContentView(parentContainer);
}
}