Layout Resources

A layout resource is another key resource commonly used in Android programming. In Android, the view for a screen is often loaded from an XML file as a resource. These XML files are called layout resources. Consider this code segment for a sample Android activity:

public class HelloWorldActivity extends Activity {

^Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); setContentView(R.layout.main);

TextView tv = (TextView)this.findViewById(R.id.textl); tv.setText("Try this text instead");

The line setContentView(R.layout.main) points out that there is a static class called R.layout, and within that class there is a constant called main (an integer) pointing to a View defined by an XML layout-resource file. The name of the XML file would be main.xml, which needs to be placed in the resources' layout subdirectory. In other words, this statement would expect the programmer to create the file /res/layout/main.xml and place the necessary layout definition in that file. The contents of the main.xml layout file could look like Listing 3-2.

Listing 3-2. Example main.xml Layout File <?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" >

0 0

Post a comment