Android setOnclicklistener parameter

后端 未结 6 1584
忘了有多久
忘了有多久 2021-02-06 07:58

I\'m a beginner to android, while setting onclick listener to a button, what does the parameter passed mean:

 btn1.setOnClickListener(new OnClickListener() {

         


        
6条回答
  •  温柔的废话
    2021-02-06 08:12

    To instantiate an object of an interface or an abstract class, you need to override all of its not implemented methods (abstract methods). You can override the abstract methods by either using anonymous class or defining a class that extends the abstract class/implements the interface and override the abstract methods. However, to make it clearer, you can do it like this:

    OnClickListener l = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
        }
    });
    btn1.setOnClickListener(l);
    

    and to use a separate class, you can do it like this:

    btn1.setOnClickListener(new MyOwnListener());
    
    // ...
    
    public class MyOwnListener implements OnClickListener
    {
        // ...
    
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
        }
    }
    

提交回复
热议问题