Monday, May 3, 2010

XML layout and R class

The user interface elements are declared in an XML file, these are compiled automatically (if you have setup your IDE correctly) into a R (for resource, i guess) class. Through R your Android program can access them.

So if your widgets and containers are specified in myMain.xml, then in your OnCreate() method of the Activity, then you use setContentView(R.layout.myMain).

If you want to access the elements in the XMl file, the element must have an android:id tag filled. To access the identified widget use findViewById by passing the numeric id found in the

XML fragment:
For the above to work the root element of the XML must declare the Android namespace.

The fragment above declares a button with text "Press" for the specified size. To access the button, in this case, use findViewById(

Button btn=(Button) findViewById(;

No comments:

Post a Comment