Recipe Declaring a Layout Programmatically

The XML layout framework in Android is the preferred method for enabling general device changes and simple development. However, sometimes it is useful to change some layout aspects programmatically—using Java, for example. In fact, the entire layout can be declared using Java. For illustration, a portion of the previous recipe's layout is shown implemented as Java code in Listing 4.4. It should be stressed that not only is coding layout in Java cumbersome, but it is also discouraged because it does not take advantage of the modular approach to resource directories where a layout can be changed simply without modification ofJava code, as discussed in the "Specifying Alternate Resources" recipe.

Listing 4.4 src/com/cookbook/programmaticlayout/ProgrammaticLayout.java package com.cookbook.programmatic_layout;

import android.app.Activity;

import android.os.Bundle;

import android.view.ViewGroup;

import android.view.ViewGroup.LayoutParams;

import android.widget.RelativeLayout;

import android.widget.TextView;

public class ProgrammaticLayout extends Activity { private int TEXTVIEW1_ID = 100011;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

//Here is an alternative to: setContentView(R.layout.main);

final RelativeLayout relLayout = new RelativeLayout( this ); relLayout.setLayoutParams( new RelativeLayout.LayoutParams(

LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT ) ); TextView textView1 = new TextView( this ); textView1.setText("middle"); textView1.setTag(TEXTVIEW1_ID);

RelativeLayout.LayoutParams text1layout = new

RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT,

LayoutParams.WRAP_CONTENT ); text1layout.addRule( RelativeLayout.CENTER_IN_PARENT ); relLayout.addView(textView1, text1layout); TextView textView2 = new TextView( this ); textView2.setText("high");

RelativeLayout.LayoutParams text2Layout = new

RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT,

LayoutParams.WRAP_CONTENT ); text2Layout.addRule(RelativeLayout.ABOVE, TEXTVIEW1_ID ); relLayout.addView( textView2, text2Layout );

setContentView( relLayout );

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Post a comment