Android Programming:Button Tutorial


Hi! I assume that you know how to set up android-sdk in eclipse.

So,Let’s start with a simple application that will recognize button click (Long,Short).

1. import

import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.view.*;

import android.widget.Toast   is use to Display message

androidtost

2. Next

Button bt1 ;
bt1=(Button)findViewById(R.id.btn);
bt1.setOnClickListener(new View.OnClickListener()

bt1 is object of Button. bt1 is specified by findViewById(XML FILE BUTTON NAME)

e.g.

<Button
android:id=”@+id/btn”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_above=”@+id/textView1″
android:layout_alignRight=”@+id/textView1″
android:layout_marginBottom=”64dp”
android:layout_marginRight=”36dp”
android:text=”Click Me” />

What to do on click??

bt1.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
prnt();
}
});

and for long click

bt1.setOnLongClickListener(new View.OnLongClickListener() {

@Override
public boolean onLongClick(View arg1) {
// TODO Auto-generated method stub
prntl();
return false;
}
});

where prnt() and prntl() are

public void prntl()
{
Toast.makeText(this, “long press”, Toast.LENGTH_SHORT).show();
}
public void prnt()
{
Toast.makeText(this,”clicked”,Toast.LENGTH_LONG).show();

}

in Toast.makeText  (this is Context, then Text to be printed ,  duration of message)

Get buttonclick code here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s