Friday, January 2, 2015

How to use Button OnClickListener in android

Button OnClickListener
android developer can declare the click event handler programmatically rather than in an xml layout by creating an View.OnClickListener object. we can assign this object to the button control or other view by calling setOnClickListener() method.

this is very helpful when we instantiate a Button widget at run time or we need to declare the click behavior in a Fragment subclass. the following example code demonstrate us how can we declare a button click event handler programmatically at run time.
activity_main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    >

    <TextView
        android:id="@+id/text_view"
        android:text="A sample text view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <Button
        android:id ="@+id/push_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Click Me"
        />

</LinearLayout>
MainActivity.java

package com.cfsuman.me.myapplication5;

import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.util.TypedValue;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = (Button) findViewById(R.id.push_button);
        btn.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                TextView tv = (TextView) findViewById(R.id.text_view);
                Button btn = (Button) findViewById(R.id.push_button);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,50);
                btn.setTextColor(Color.RED);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

this image shows the initial state of this example application.


after clicking the button widget the TextView changed its text size and the button widget also changed its text color. setTextColor() method allow us to change a widget's text color. setTextSize() method change the text size of a view. to change the textView widget's text size we uses the android.util.TypedValue class. this android utility class allow us to setting the text size by scaled pixel (sp).


the bellow code in java file allow us to declare an click event handler for button widget programmatically. in this section we also perform some action when someone click the button widget.

modified code on java file

Button btn = (Button) findViewById(R.id.push_button);
btn.setOnClickListener(new View.OnClickListener()
{
 public void onClick(View v)
 {
  TextView tv = (TextView) findViewById(R.id.text_view);
  Button btn = (Button) findViewById(R.id.push_button);
  tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,50);
  btn.setTextColor(Color.RED);
 }
});

in the bellow xml code section describe the button widget's attributes. this xml layout file contains no onClick attribute. we want to set an onclick event handler at run time.

parts of xml layout file

<Button
 android:id ="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:text="Click Me"
 />
More android examples