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 =)
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.