Skip to content Skip to sidebar Skip to footer

Android: Create Click Listener Programmatically With Anonymous Class

I see a few examples of making a TextView clickable by setting onClick='clickHandler' and clickable='true'. Is there a way to use an anonymous class instead of hard coding a click

Solution 1:

There you go

TextView tv = (TextView)findViewById(R.id.textview);
tv.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // do whatever stuff you wanna do here
    }
});

Solution 2:

public void setClickable (boolean clickable)

Enables or disables click events for this view. When a view is clickable 
it will change    its state to "pressed" on every click. Subclasses should 
set the view clickable to visually react to user's clicks.
Related XML Attributes

TextView tv = new TextView(this);
tv.setClickable(true);
tv.setOnClickListener(new OnClickListener(){
   public void onClick(View v) {
   }
});

Solution 3:

you can set click listener like this

tv.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    })

Solution 4:

You can use an anonymous class but you need to implement the default listener provided. Create a custom listener class that implements the OnClickListener class and pass object into the setOnClickListener method. Here, you have an opportunity to pass global variables to be used inside the onClick method.

You may find this useful, Create a custom event listener in Android


Post a Comment for "Android: Create Click Listener Programmatically With Anonymous Class"