Wednesday, May 6, 2009

Android's Button Onclick Event:Button.OnClickListener()

I came from Asp.net background, and I really didn't have any idea on how to develop mobile phone applications. I didn't see any documentation on how get an event for OnClick on Android SDK, this most simple feature is can not be automatically generated by Eclipse, you have do it on your own.

in the \res\layout\main.xml Create the button

<button
id="@+id/TestButton"
layout_width="fill_parent"
layout_height="wrap_content"
layout_marginleft="30dip"
layout_marginright="30dip"
text="Test Button">

And you can reference it like this from code behind

---------------------------------------------------------
package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;

public class HelloAndroid extends Activity {
private Button btnFromGallery;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}

protected void initControls()
{
btnFromGallery = (Button)findViewById(R.id.TestButton);

btnFromGallery.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ DoWork(); }});
}

protected void DoWork()
{
//Do whatever you need to do here
}
}
-------------------------------------------------------------------

This may look simple but it was very hard to find it online, I hope google would create more examples in the future.

3 comments:

  1. that's what I've been looking for, thanks a lot :)

    ReplyDelete
  2. I just tried this thing but when i run the app it does not run and it closed forcefully.

    could you please help?

    my android OS version is 2.2

    ReplyDelete
  3. i tried given code but whenever i run the application it doesn't run & i have to forcefully close application

    ReplyDelete