Button Listener – Make the cat start Meowing

We might have thought, how come when we click a button some action is performed in Android phone. Here in this post, we are going to discuss how to handle button events in Android.

Before proceed with the post, I would like to thank everyone who gave constant feedback for the past three posts. I expect everyone to let me know if you come across any difficulty while creating the application.

Please subscribe to this blog to keep getting updates when new post is added.

What are we going to develop?

We are gonna develop a simple application which has one button  that covers whole  layout of the app. When you click/tap on the button, ‘Meow’ sound will be played, to be more appropriate we will keep ‘Cat’ image as background of the button. 🙂


Quick Links

Project Structure

Before start with the application development, download code from here to proceed with the below listings.

I assume you created new project for this application.I created the project with name “ButtonListener”, just follow the same name. Default main.xml will look something like below image:

Code Listings

Let us start with the layout creation: So we will have one button and the properties are:

  1.  Open main.xml under /res/layout folder and remove default textview from it
  2. Add button to the layout, you can create either in two ways: 1. Drag and drop the button 2. with the help of intellisense [Ctrl+Space]  in main.xml edit window, do Ctrl+Sapce and type B to look for Button.
  3. Now main.xml will look like:

<?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” >

<Button android:id=”@+id/button1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Button” />

</LinearLayout>

As we already discussed, button will cover entire layout of the application. So make layout_width property  to “match_parent”.

Button covered entire width of the phone but have to cover entire height, so make layout_height property to “match_parent”

Remove button text property and add android:background property with cat image location. Place Cat image under /res/’drawable-hdpi folder. Assign android:background property with value “@drawable/kitty” where kitty is the name of the image placed in images folder.

Final layout xml:

<?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” >

<Button android:id=”@+id/button1″ android:layout_width=”match_parent” android:layout_height=”match_parent” android:background=”@drawable/kitty” />

</LinearLayout>


[pgsubscribe]
We have to place “Meow” audio file in the /res/raw/ folder , if raw folder doesn’t exist create one and place the audio file. Right click and save the Meow audio file.

We are done with the layout creation and adding resources for our application. Now we are going to write few lines of code to bring the cat alive. 🙂

Create two instance objects in ButtonListenerActivity class, one for referring the button we created and other for calling android in-built mediaplayer.

//Object going to refer the button which we created
Button meowBtn; 
//Call and Use android in-built media player
MediaPlayer mPlayer;

Initialize the objects which we created in onCreate() method . The onCreate() method will be called when we launch application.

//Refers the button with the help of id
meowBtn = (Button) findViewById(R.id.button1);
//Prepare media player with sound file available in /raw folder
mPlayer = MediaPlayer.create(ButtonListenerActivity.this, 
          R.raw.meow);

Add listener for button in onCreate() method

//Traditional Java Event Listener
meowBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)//When button is clicked
try {
mPlayer.start(); //Mp3 will be played
} catch (Exception e) {
//Run time error will be logged
Log.e("ButtonListenerActivity", "error: " + 
                            e.getMessage(), e); 
}
}
});

We have to release the media player when the application is closed or gone idle. Release the mediaplayer in onDestroy() method:

protected void onDestroy() {
super.onDestroy();
//if mediaplayer is still holding mediaplayer
if (mPlayer != null) {
// release the mediaplayer
mPlayer.release(); 
//Assign it with null value
mPlayer = null; 
}
}

Final look of the class:

package com.prgguru.android;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class ButtonListenerActivity extends Activity {
protected static final String TAG = "ButtonListnerActivity";
Button meowBtn;
MediaPlayer mPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
meowBtn = (Button) findViewById(R.id.button1);
mPlayer = MediaPlayer.create(ButtonListenerActivity.this, 
                                                 R.raw.meow);
meowBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
mPlayer.start();
} catch (Exception e) {
Log.e("ButtonListenerActivity", "error: " + e.getMessage(),e);
}
}
});
}
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}

[pglinkadssmall1]

Demo

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.

Expected output:

Tap on the cat, it will say “Meow” . 🙂

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android  is the installation file simliar to exe in windows.

 


Share with your friends if you feel this post is interesting!! 🙂

Reference:

Media Player

Suggested posts for further reading

[pglinkadssmall]

[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • Satheesh

    Nice…

  • Aravind Sagar

    Great work.:)
    In the “add listener for OnCreate() method” , in the code given, one ‘{‘ is missing. It is there in the final look of th class though.

    • Hey Aravind, Thanks for noticing it!!.. I added the curly brace.. 🙂

  • Ganesh

    Thanks for such a nice tutorial.

    • Welcome.. Do visit other blog posts too which would be useful for you. 🙂

  • PRATHAP

    Thanks for share this…its really helpful for fresher android developer…

    I want play a local vedio using a upload button please help me

    Thank you .

  • Saravana

    superb…………
    keep it up…….

  • newbie

    awesome!
    Thanks for the tutorial!

  • mrudula

    awesome 🙂

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares