So far, all the sections we see in the UI are implemented through XML. As mentioned earlier, in addition to using XML, you can also use code to implement the UI. This method is very useful. For example, your UI needs to be generated at runtime. For example, if you are writing a "movie ticket booking system", your program uses the button Buttons to display the seats in each cinema. In this case, you need to dynamically generate the UI based on the actual situation.
The following example shows how to dynamically generate the UI in the Activity by encoding.
1. Create a project: UICode.
2. Code in UICodeActivity. java.
[Java]
Public class UICodeActivity extends Activity {
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
// SetContentView (R. layout. main );
// View parameters
LayoutParams params =
New LinearLayout. LayoutParams (
LayoutParams. FILL_PARENT,
LayoutParams. WRAP_CONTENT );
// Create a layout
LinearLayout layout = new LinearLayout (this );
Layout. setOrientation (LinearLayout. VERTICAL );
// Create a TextView
TextView TV = new TextView (this );
TV. setText ("This is a TextView ");
TV. setLayoutParams (params );
// Create a Button
Button btn = new Button (this );
Btn. setText ("This is a Button ");
Btn. setLayoutParams (params );
// Add TextView to the layout
Layout. addView (TV );
// Add a Button to the layout
Layout. addView (btn );
// Create attributes used by the Layout
LinearLayout. LayoutParams layoutParam =
New LinearLayout. LayoutParams (
LayoutParams. FILL_PARENT,
LayoutParams. WRAP_CONTENT );
This. addContentView (layout, layoutParam );
}
}
3. Perform F11 debugging as follows.
In this example, the setContentView () method must be commented out to prevent the Activity from loading the UI view in main. xml.
Then, create a LayoutParams object, which specifies the layout attribute.
[Java]
LayoutParams params =
New LinearLayout. LayoutParams (
LayoutParams. FILL_PARENT,
LayoutParams. WRAP_CONTENT );
Create a LinearLayout object that contains all views in the activity.
[Java]
LinearLayout layout = new LinearLayout (this );
Layout. setOrientation (LinearLayout. VERTICAL );
Then, create a TextView and a Button.
[Java]
TextView TV = new TextView (this );
TV. setText ("This is a TextView ");
TV. setLayoutParams (params );
Button btn = new Button (this );
Btn. setText ("This is a Button ");
Btn. setLayoutParams (params );
Then, add them to the LinearLayout object.
[Java]
Layout. addView (TV );
Layout. addView (btn );
At the same time, you must create a LayoutParams object for use by the LinearLayout object.
[Java]
LinearLayout. LayoutParams layoutParam =
New LinearLayout. LayoutParams (
LayoutParams. FILL_PARENT,
LayoutParams. WRAP_CONTENT );
Finally, add the LinearLayout object to the Activity.
[Java]
This. addContentView (layout, layoutParam );