Android: how to handle button click

后端 未结 10 2214
刺人心
刺人心 2020-11-27 11:08

Having a solid experience in non-Java and non-Android area, I\'m learning Android.

I have a lot of confusion with different areas, one of them is how to handle butt

10条回答
  •  清酒与你
    2020-11-27 11:14

    Most used way is, anonymous declaration

        Button send = (Button) findViewById(R.id.buttonSend);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // handle click
            }
        });
    

    Also you can create View.OnClickListener object and set it to button later, but you still need to override onClick method for example

    View.OnClickListener listener = new View.OnClickListener(){
         @Override
            public void onClick(View v) {
                // handle click
            }
    }   
    Button send = (Button) findViewById(R.id.buttonSend);
    send.setOnClickListener(listener);
    

    When your activity implements OnClickListener interface you must override onClick(View v) method on activity level. Then you can assing this activity as listener to button, because it already implements interface and overrides the onClick() method

    public class MyActivity extends Activity implements View.OnClickListener{
    
    
        @Override
        public void onClick(View v) {
            // handle click
        }
    
    
        @Override
        public void onCreate(Bundle b) {
            Button send = (Button) findViewById(R.id.buttonSend);
            send.setOnClickListener(this);
        }
    
    }
    

    (imho) 4-th approach used when multiple buttons have same handler, and you can declare one method in activity class and assign this method to multiple buttons in xml layout, also you can create one method for one button, but in this case I prefer to declare handlers inside activity class.

提交回复
热议问题