Access Android View in Activity

In Android Get View Defined in XML in Activity Code

The UI screens for an App can be designed outside of the code. They are stored in XML files. This eases support for multiple screen sizes and types and helps with software maintenance. Classes in the Android SDK have methods used to access the UI components. Screens are composed of various implementations of the Android View class. The major sub-classes for Views are widgets and ViewGroups. The widget class is not to be confused with Widgets that can be added to the Android home screen. Instead View widgets are the normal components with which the Android device users interact, including the ButtonCheckboxEditText (a text box), ImageViewRadioButtonProgressBarTextView (label) and many more. Several widgets sit in a ViewGroup which provides a container for laying out components. Different ViewGroups provide different types of layouts, including RelativeLayoutLinearLayoutScrollViewWebView and others. ViewGroups can contain other ViewGroups as well as widgets therefore building complex displays by nesting different Views is possible.

Create a Basic Android Screen

A Simple Android ScreenFor this tutorial create a new, simple Android App project and call it Button Demo (if you don’t know how see Your First Android Hello World Java Program). A simple screen that just has a button on it was created using the starting layout, we kept the default layout name of activity_main.xml. In Eclipse use the Package Explorer to open the activity_main.xml file (in the res/layout folder). Using the Graphical Layout view (selected via the tabs at the bottom of the editor window) delete the TextView, showing Hello world!, and drag and drop a Button from the Form Widgets folder onto the screen. This screen’s code is stored in the activity_main.xml file:

To show how this view is accessed from the App’s code the text on the button will be changed and it displays a message when it is clicked.

An Explanation of Android’s View Ids

The important part of the screen definition, when accessing it in the code, is the android:id attribute part of the Button widget. Here it is set to @+id/button1, the plus sign (+) tells the Android SDK that it is a new id. When defining an id for a widget it is in the form of @+id/name, think of it as @ (address) (adding new) id/name (unique identifier). In other words you are adding an id that uniquely addresses the screen element. A widget or View does not need an id if it is not going to be accessed in code. It does need an id to be accessed from code or for automatic state saving. If in doubt add an id, it usually helps with future App maintenance. Give the widget a relevant id name, for example a TextView showing a cell phone number should be called something like textCellPhone and not textView24.

Using the View Id to Get a View Reference

Browse R ClassIn the Android App a Java public class called R is generated from all the defined resources. The ids given to screen elements are added to the public id class in the R class as an integer values, chosen by the Android SDK. Thus this value can be accessed  using In this example the Button id of button1 is used in the code using The id values are declared static final int therefore cannot be changed at execution time by your App’s code. The class can be examined by looking in the gen folder in the project, it should not be manually changed. Occasionally the class gets our of sync with the code. Choosing Clean from the Project menu often fixes it, or restarting Eclipse.

When the App’s main Java class is opened under the src folder, here we are using the default class name of MainActivity, it will be seen that it extends the Activity class. The Activity class provides a method called findViewById. This takes the ids from the R class and returns a reference to the relevant View. This is then cast to the appropriate object, in our case a button. Therefore we get a reference to the Button using this code:

The cast to the Button class will require import android.widget.Button; adding to the imports section of the file. Eclipse can do this automatically, hover the mouse over the red line that appears under Button and click on the Import ‘Button’ (android.widget) option in the pop-up window.

Using the Reference Returned by findViewById

With the reference return by findViewById cast to the appropriate widget or View object the interface elements can be manipulated using their class methods. For example the text for the Button is changed using the button’s setText method:

To handle the button being pressed an instance of the OnClickListener class must be attached to the button reference, using the well named setOnClickListener method (which is provided by the View class). The implementation of OnClickListener takes an onClick function, this is what is called when the View’s click occurs. Here is a definition of an onClick function, being passed into the constructor of an OnClickListener implementation, that simply displays a message, :

Imports for View and Toast need adding in a similar manner to the Button import. The onClickListener is then attached to the button:

Notice that the onClick function takes a View object as a parameter, here called arg0.  This parameter is a reference to the pressed View. Again this can be cast to the screen element pressed, here a Button, so that the clicked item can be accessed in the onClick function:

Using an Anonymous Class with findViewById

If you need to access a reference to a View only once it saves code to use an anonymous class. This is where you use the return value of findViewById but do not assign it to a declared class variable. Behind the scenes Java still creates a class but it cannot be seen, hence it is anonymous. This is done by wrapping the cast and call to findViewById in brackets and using it like it is a class itself. Thus this:


Using Module Level View References

If a View is going be accessed in several place in a Java file declare the View variable at the module level. The following is source code is our final class for our demo. Notice how the btn variable is declared at the start of the class definition, is assigned in the onCreate method (after the call to setContentView), and is then used in the HandleClick class with out needing to cast the arg0 parameter to its own Button reference:

An Android Simple Button Demo

See Also

Different Ways to Code Android Event Listeners

Saving an Activity’s State when it’s Interrupted

Leave a Reply

Your email address will not be published. Required fields are marked *

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.