Which one of the ways has better performance, or is a good programming practice, making the holder activity extend OnClickListener and make a Switch() clause for getItemId() or making one OnClickListener for each one of the buttons or widgets that need it or making separated classes in the same (or another) package that implements OnClickListener and instance them in the activity?

  • 1
    Why don't you measure the performance of both? Aug 5, 2014 at 2:01
  • 1
    I don't know how to measure it. I have done each one but they seem to be the same...
    – El_Mochiq
    Aug 5, 2014 at 2:04
  • 3
    Premature optimization, root of all evil, etc.
    – Doval
    Aug 7, 2014 at 13:39
  • Which one do you think will be easier to debug and maintain?
    – TomG
    Aug 7, 2014 at 18:48

1 Answer 1


Here are the best and better programming way for to work with button /any other widget

  1. Declare Button/ any other widgets Object outside from the Activity life cycle method; mostly after declaration of the public class like this

    public class MainActivity extends Activity {

    Button button;

  2. Always define inside the onCreate(Bundle savedInstanceState) method; because it's guaranteed that onCreate() always call so therefore it's better to define inside onCreate() method.

Here is the complete Code example

public class MainActivity extends Activity {

Button button;

protected void onCreate(Bundle savedInstanceState) { 

    button=(Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            //Any thing you want here


On the above I have used anonymous class onClickLListener that is the nested class of View class; so you can also use separate class Avoid to make switch statement because it's make your like spaghetti like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.