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 R.id.something.

XML fragment:
<Button
android:id="@+id/button1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:text="Press"
/>
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(R.id.button1).

Eg.
Button btn=(Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
...
...

No comments:

Post a Comment