Skip to content Skip to sidebar Skip to footer

Which One Is Best Way To Implements Onclicklistener In Android?

which one is best way to implements OnClickListener Interface in Android. /*- First - */ public class EmployeeActivity extends Activity implements OnClickListener { /** Called

Solution 1:

which one is best way to implements OnClickListener Interface in Android

This depends solely on what fits best for you as the developer. They all work the same and you even have another option to declare onClick in xml. I like the first especially if you will have multiple Buttons that you want to share functionality. But a better way to do the first is to switch on the id of the View being clicked. Something like

@OverridepublicvoidonClick(View v) {
    intid= v.getId();
    switch (id)
    {
        case R.id.btnUpdate:
           // do workbreak;
        case R.id.btnEdit
           // do work for edit buttonbreak;
    }
    // put shared functionality code like starting an Activity, calling a method, etc...
}

The second I like to use if there is only one or two Buttons and they have completely different functionality. I think this way makes the code look more cluttered and messy if you have too many Buttons. But these all work the same and won't change the performance of your app.

Solution 2:

Neither one is "better." Which one you use is a personal choice, and will depend on which one fits your coding style.

The advantage to the second method is that you can have a unique OnClickListener for each View. The advantage to the first option is that all of your onClick() code is in one place.

Solution 3:

The first method is good. But rather than if-else. use switch case.

@OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    ButtonbtnUpdate= (Button)findViewById(R.id.btnUpdate);
        ButtonbtnEdit= (Button)findViewById(R.id.btnEdit);

        btnUpdate.setOnClickListener(this);
        btnEdit.setOnClickListener(this);

    @OverridepublicvoidonClick(View v) {

       switch(v.getId())
      {
      case R.id.btnUpdate:
        //your workbreak
}

Solution 4:

Your first example is incorrect, you shouldn't compare the objects like that. You need to do something like:

switch(v.getId()) {
    case R.id.yourButton:
        ...
}

They are both equivalent for the most part, except the second allocates a new object for each listener. If I have lots of buttons on one screen I like to organize it like you have in the first example to avoid more boilerplate code.

Solution 5:

It depends upon the number of elements that you have in your current activity. I prefer the second method for few buttons (2 or 3). Any thing more than that I use first method and ofcourse with a switch statement.

Post a Comment for "Which One Is Best Way To Implements Onclicklistener In Android?"