-1

i'm using a navigation drawer in android and i've build a listener of two ways. but in all programming codes how would be better code?

1) the first method i implements a class

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{  

 NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//CODE
}
}

2) in the second way i just use a instance.

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    //CODE
                }
            }
    );

what do you think is better and why? Thanks =)

Mike Brian Olivera
  • 1,414
  • 1
  • 16
  • 21

3 Answers3

1

Actually it will totally depend on your implementation.

1)For case 1, suppose you are implementing a class for a view. Then, you will be able to use the implemented methods only for one time inside this class.

2)Case 2 allows you to create multiple functions.

Take example from View.OnClickListener, if you will implement this, you will be able to use onClick method only for one time inside the class. So, all views inside this class will use this same onClick method.

public class MainActivity implements View.OnClickListener {
    public void onClick(View v) {
        .... 
    } 
 }

But if you will use setOnClickListener() , you can implement different(or same) methods each time.

N Kaushik
  • 2,198
  • 18
  • 29
0

Actually, choosing one or the other is a combination of your personal taste, the MainActivity's responsibility, and maybe performances.

I'm usually in favor of composition, and try to avoid mixing a lot of responsibility in the same class. The listener you are implementing could be hidden behind a factory or something, making the MainActivity's code simpler and easier to maintain.

Regarding performances, you should probably opt for your first choice, but as a matter of fact, instantiating one more class should not have any significant impact.

Francis Toth
  • 1,595
  • 1
  • 11
  • 23
0

In this case I always use first method, because inside fragments in method onAttach I can check the activity to implementing needed interface for interaction with this fragment and, for example, throw exception as signaling that you must implement the interface. Besides that, in this case you don't need to write methods like setListener. Of course, it's my imho for this concrete case.

kolombo
  • 1,091
  • 9
  • 14