I usually code
Button button1 = (Button)findViewById(R.id.start1);
button1.setOnClickListener(mStart1Listener);
Button button2 = (Button)findViewById(R.id.start2);
button2.setOnClickListener(mStart2Listener);
But in android sample, I found these in ServiceStartArgumentsController.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_start_arguments_controller);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.start1);
button.setOnClickListener(mStart1Listener);
button = (Button)findViewById(R.id.start2);
button.setOnClickListener(mStart2Listener);
button = (Button)findViewById(R.id.start3);
button.setOnClickListener(mStart3Listener);
button = (Button)findViewById(R.id.startfail);
button.setOnClickListener(mStartFailListener);
button = (Button)findViewById(R.id.kill);
button.setOnClickListener(mKillListener);
}
What’s the difference between them, and why one button can add multiple ClickListener
A View can only have one OnClickListener. The second approach is just re-using the variable
button, notice the third line:It overrides the previous value of
buttonwith a new Button and the new Button will be assigned the next OnClickListener.