How to use OnClickListener in android

In android application developmentĀ  we can use OnClickListener in two ways. In first method is add OnClickListenerto each button individually. Imagine that you have several buttons like below image.

Now you want to use OnClickListener function in each button. Code snippet can be shown as

package com.lister;

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

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

        ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1);
        btn1.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Toast pieceToast= Toast.makeText(getApplicationContext(), "Image Button One Clicked", Toast.LENGTH_SHORT);
				pieceToast.show();		

			}
		});

        ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
        btn2.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Toast pieceToast= Toast.makeText(getApplicationContext(), "Image Button Two Clicked", Toast.LENGTH_SHORT);
				pieceToast.show();		

			}
		});

        ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3);
        btn3.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Toast pieceToast= Toast.makeText(getApplicationContext(), "Image Button Three Clicked", Toast.LENGTH_SHORT);
				pieceToast.show();		

			}
		});

        ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4);

        ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5);

    	}

	}

As my example you can see you want to use OnClickListener in each and every button you have to implement lot of codes. But when you implement OnClickListener interface to your Action class then you can minimize your code like below

package com.lister;

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

public class Main extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1);
        btn1.setOnClickListener(this);

        ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
        btn2.setOnClickListener(this);

        ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3);
        btn3.setOnClickListener(this);

        ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4);
        btn4.setOnClickListener(this);

        ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5);
        btn5.setOnClickListener(this);

    }

	public void onClick(View v) {

		Toast pieceToast=null;

		switch (v.getId()) {

		case R.id.imageButton1:
			pieceToast= Toast.makeText(getApplicationContext(), "Image Button One Clicked", Toast.LENGTH_SHORT);
			pieceToast.show();			
			break;

		case R.id.imageButton2:
			pieceToast= Toast.makeText(getApplicationContext(), "Image Button Two Clicked", Toast.LENGTH_SHORT);
			pieceToast.show();
			break;

		case R.id.imageButton3:
			pieceToast= Toast.makeText(getApplicationContext(), "Image Button Three Clicked", Toast.LENGTH_SHORT);
			pieceToast.show();
			break;

		case R.id.imageButton4:			
			pieceToast= Toast.makeText(getApplicationContext(), "Image Button Four Clicked", Toast.LENGTH_SHORT);
			pieceToast.show();
			break;

		default:
			break;
		}

	}

	}

This is very good practice when we are more button in our application. Not only image button you can use any GUI widget and use this technique when you are coding your Android application.

2011 in review

The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.

Here’s an excerpt:

The concert hall at the Syndey Opera House holds 2,700 people. This blog was viewed about 10,000 times in 2011. If it were a concert at Sydney Opera House, it would take about 4 sold-out performances for that many people to see it.

Click here to see the complete report.

How to intergrate zxing barcode scanner into our project

Hi , i am doing a project which my android enable mobile use to scan the bar-code using its in build camera. When i search on this topic i found that there is a great free and open source application call ZXing. This application allow users to access the Scan class using Intent. I am still studying about develop android application development.But after search on the internet i found the solution.Now i have created a simple application on how to do id. I created sample video of demonstration on my Huawei U8180 device.

You must install the ZXing to your device from android market.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="match_parent"
	android:layout_height="match_parent" android:background="@drawable/bg">

	<Button android:text="SCAN NOW" 
    android:id="@+id/btnSearch" 
    android:layout_width="150px" 
    android:gravity="center_vertical|center_horizontal" 
    android:layout_height="100dp" 
    android:layout_gravity="center_vertical|center_horizontal|center" android:textStyle="bold" android:textSize="25dp" android:layout_marginTop="150dp">
</Button>
</LinearLayout>

Now my main class like this.

package com.br;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {
    /** Called when the activity is first created. */

	Button myButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myButton =(Button)findViewById(R.id.btnSearch);

        myButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		      //  intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
		        startActivityForResult(intent, 0);

			}
		});
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {

            	//String result =intent.getAction();
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                //Toast andEggs = Toast.makeText(Main.this, contents, Toast.LENGTH_SHORT);
    			//andEggs.show();
                AlertDialog alertDialog = new AlertDialog.Builder(Main.this).create();
                alertDialog.setTitle("Barcode Results");
                alertDialog.setMessage(contents+"\n"+format);
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

					}
				});
                alertDialog.setIcon(R.drawable.barcode);
                alertDialog.show();

                // Handle successful scan
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
    }
}

Now my AndroidManifest.xml file look like this.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.br"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>

    <application android:icon="@drawable/barcode" android:label="@string/app_name">
        <activity android:name=".Main"
                  android:label="@string/app_name"

                  android:configChanges="orientation|keyboardHidden"
                  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                  android:windowSoftInputMode="stateAlwaysHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

I think now you can understand how to use ZXing library in our project.This is the greatest library i ever saw in my life for mobile application development.
Sources

  • http://damianflannery.wordpress.com/2011/06/13/integrate-zxing-barcode-scanner-into-your-android-app-natively-using-eclipse/
  • http://zxing.appspot.com/generator/ (For create a QR code)
  • http://code.google.com/p/zxing/