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

TextViewtv= (TextView)findViewById(R.id.textview);
tv.setOnClickListener(newOnClickListener() {

    @OverridepublicvoidonClick(View v) {
        // do whatever stuff you wanna do here
    }
});

Solution 2:

publicvoidsetClickable (boolean clickable)

Enables or disables click events forthis 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(){
   publicvoidonClick(View v) {
   }
});

Solution 3:

you can set click listener like this

tv.setOnClickListener(newView.OnClickListener() {

        @OverridepublicvoidonClick(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"