Pr.Pg Next Pg

Referencing the XML IDs tutorials

Setting up the Variables in Java

  • The XML entities are basically just Views.

  • To add functionality into them, we need to access them in the Java files

  • We first go to the file in the src folder .

  • We define new variables, the same we you do in a normal java code.

  • In this example, we basically are going to have a Button and a TextView which will display how many times a button has been clicked.

  • The will look like this after defining the variables.


package com.example.helloandroid;


import android.os.Bundle;


import android.content.Intent;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;


public class MainActivity extends Activity {

int counter = 0;

Button click;

TextView display;



protected void onCreate(Bundle savedInstanceState) {



click = (Button) findViewById(;

display = (TextView) findViewById(;


click.setOnClickListener(new View.OnClickListener() {



public void onClick(View arg0) {

// TODO Auto-generated method stub

display.setText("I have been clicked " + (++counter) + " times");








MainActivity Class

  • We had declared a activity name as MainActivity while creation of the project.

  • The Eclipse makes a java file of every activity.

  • In this file there is a class named MainActivity which extends Activity which basically means that it is a type of Activity and can use the methods and variables used in the Activity class.

  • There is a method onCreate() which is always called whenever an Activity starts.

  • There is another method called the onCreateOptionsMenu() which is called when option menu is displayed. For that you need to add options into your Application. For our example this method is of no use.




  • We have declared an integer type variable counter which will keep a track of how many times the Button is clicked.

  • We have declared a variable called click of the type Button.

  • We have alse declared a variable called display of the type TextView.

  • In the method onCreate(), we assign them the reference to the XML buttons which we had created earlier with the help of the IDs assigned to them.


Adding onClickListener

  • To assign an action to the button click when it is clicked, we have to setOnClickListener for it.

  • This method takes in parameter of type onClickListener and hence we create an object in the parameter itself.

  • Since the class belongs to the View hierarchy we write View.OnClickListener().

  • It has a method called onClick in which we can define the action to be performed when the button is clicked.

  • In this case we change the text of the TextView to display the number of times the button has been clicked using the setText() method.


Pr.Pg border                                              Next Pg