Android setOnclicklistener parameter

后端 未结 6 1521
忘了有多久
忘了有多久 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 07:58

    OnClickListener is an interface and by using new OnClickListener() as parameter for btn1.setOnClickListener it is actually creating an Anonymous Inner Class which implements OnClickListener. And the method onClick must need to be declared since its an abstract method inside that interface class. Any code you write inside onClick will be executed when the button is pressed.


    Update

    to do it using Anonymous inner class in an object:

    //declaring OnClickListener as an object
    private OnClickListener btnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
    
        }
    };
    
    //passing listener object to button
    btn1.setOnClickListener(btnClick);
    

    to do it without using Anonymous class:

    public class YourActivity extends Activity implements OnClickListener {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
           Button b = new Button(this);
    
           //setting listener to button
           b.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
    
        }
    }
    

    The only difference between these approaches is, if your button contains click event code which is supposed to be valid/available for that button only, then you may use inner class as you are doing in your code (because its easy to do right away). However if there are multiple buttons which require same code to be executed on onClick event then you may define listener as an object and pass it to them.

提交回复
热议问题