Wednesday, April 27, 2011

Clicking a Button

This isn't a copy and paste tutorial that your accustomed to seeing in this section. I thought I would step up and show one of my skills since this section seems lacking. I will probably write more Android tutorials including how to create the APK file to actually put them on an Android. In this tutorial we are going to click a button. Simple I know, but most can't even get past this. If you don't know anything about Java or event listeners then you might want to go read up on it before you continue. Also in this tutorial you will use Toast to show that you clicked the button since it's the easiest way.

Android's toast is a little popup message that fades in and out as we call it. We can control it's fade time and some other features as indicated on the developer page but that isn't what we are focusing on here. We are focused on actually getting one to display after a button has been clicked. Toast is a view.

The first thing we need to do is add a button to our layout. Select the XML file from the folder tree on the left (in the Package Explorer) and double click (open) the XML file.

The file should load in the pane on the right hand side. If this is a new project delete the default text that comes with it. If you delete the text here be sure to delete it from the app_strings also. Not deleting it from app_strings won't damage the application but it's nice to keep it clean. Click and drag the button onto the form.

Now change the width so it's not so ugly.

 Now that our button's name is button1. We are going to add another library to reference at the top witht he rest that will give us access to use the OnClickListener event handler.

import android.view.View;
import android.widget.Button;
import android.widget.Toast;

create a button and locate our button in the interface and apply it tot he newly created button.

final Button btn = (Button) findViewById(;

then add an eventlistener to it

btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(), "Button clicked!", 100).show();

It should be ready to go, here is what the end result s hould look like. I have also attached the project files for it tot his post.

No comments:

Post a Comment