user470763
user470763

Reputation:

Can't extend OnClickListener - what's an alternative?

I'm quite new to Android. In my activities when I need to detect a tap on a button I implement OnClickListener. In my current Activity I have to implement 'YouTubePlayer.OnInitializedListener' so I can't extend OnClickListener. How do I detect click events?

Upvotes: 2

Views: 798

Answers (4)

Deepzz
Deepzz

Reputation: 4571

public class MyActivity extends Activity implements OnClickListener, YouTubePlayer.OnInitializedListener
{
   //Your code here

    button = (Button) findViewById(R.id.btn);
    button.setOnClickListener(this);


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

    }
}

Upvotes: 2

Savv
Savv

Reputation: 431

As everyone else said, OnClickListener is an interface so you'll have to implement it, not extend. But if you're still looking for an alternative, try using it as an anonymous inner class:

button.setOnClickListener(new OnClickListener()
{
     public void onClick(View v)
     {
          //do stuff when clicked
     }
}
)

Upvotes: 2

Dinesh Kumar
Dinesh Kumar

Reputation: 1293

Try this code

 public void addListenerOnButton() {
        button = (Button) findViewById(R.id.button_id_in_xml);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {

            //Do your stuffs   

            }
        });
    }

Upvotes: 2

Blackbelt
Blackbelt

Reputation: 157467

Actually View.OnClickListener is an interface. you havo to implements it, not extend. Java does not support extending from multiple class, but you can implement multiple interfaces

Upvotes: 6

Related Questions