Friday, January 2, 2015

How to use TextView onClick event in android

TextView onClick event
TextView widget display text to user. optionally a textview allow app user's to edit text. by default, a TextView is not allowed to use as a text editor. a textview is also non clickable. that means by default a textview perform no action when someone click the view.

to enable a TextView as clickable we need to set the TextView android:clickable attribute value to 'true'. by default, android:clickable attribute value is 'false'. after making a TextView to clickable, we can define an click event handler for TextView widget. TextView click event handler act similar as a push button widget and other android widgets.

in the view class, setClickable() method also allow us to convert a non clickable TextView to a clickable TextView programmatically at run time. this method require to pass a boolean parameter. if we set this setClickable(boolean) method value to 'true', then it will render the TextView widget as a clickable view. so this method programmatically enable or disable click event for a view.

android app developers also can define onClick event handler for a TextView control programmatically rather than xml layout file. to declare click event programmatically for a TextView widget we need to use the setOnClickListener() method. this method create a new OnClickListener object for the TextView widget.


        android:text="A clickable text view"



import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.view.View;

public class MainActivity extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {

    public void perform_action(View v)
        TextView tv= (TextView) findViewById(;

        //alter text of textview widget
        tv.setText("This text view is clicked");

        //assign the textview forecolor

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

    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 == {
            return true;

        return super.onOptionsItemSelected(item);

following output image display the initial state of example application. we simply generate a textview widget.

when someone click the TextView widget, it change its text color to green. the following image show the clicked textview.

More android examples