Java – OnClickListener good practice

android-developmentjavaprogramming practices

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?

Best Answer

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;


@Override
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

    button.setOnClickListener(new OnClickListener() {

        @Override
        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.