Sunday, July 1, 2012

Access UI in Android Application Development

This summer I took a class in Android application development with Java. Coming into the experience I had an extensive knowledge with C++ and the Qt framework as well as Swing and Awt which are Java-specific. Qtcreator, a popular Qt IDE, used to make it very simple to access and change the ui using (ui->objname). With Android no such object was generated with the Eclipse IDE, which is the most popular tool for Android application development. I will assume that you are using Eclipse and ADT since that is the most popular choice for developing apps.

The Example
We have a grid layout with a Button called "Button1" in the middle of it. We are going to change the text from the Activity from which it is made.

The Implementation
Down to the business. We need to first access the button object using something called "findViewById()".

In Eclipse there is a variable named "R" that relates to the generated Dalvik Java. To alter the UI, we need to go through this "R" variable to get the ID of a object. The ID is the name given to the object in the layout xml file.

First off, make a Button that will be assigned to the button in the application. (Button b = new Button()). You need to import android.widget.Button to do this. Then, assign it to the button in the layout like this (inside onCreate is a good place to do this. After setContentView) (b= (Button)findViewById(R.id.Button1). This assigns b to the button with that ID from the XML. It is neandroid.wiget.buttoncessary to cast it to a Button since it is just finding the view by ID. Now you have access to all of the methods for that button. To change the text just use the "setText()" method. (b.setText("Button Text")).

Here is the condensed version of all of this as a note:

No comments:

Post a Comment