Reputation: 7936
I have to set the listener for a NavigationView
in my main class. But the main, will containt a lot of stuff, and I want to have it the most "separated" possible.
So I will do listeners in their own java files, to something like:
navigationView.setNavigationItemSelectedListener(new NavigationListener());
The problem comes, that I have to call getSupportFragmentManager
, but is not accesible, so, I suppose that I need to do something like: context.getSupportFragmentManager
to make ir "work".
But I don't know how to get the context.
How can I get it?
ListenerClass:
public class NavigationListener implements NavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
boolean fragmentTransaction = false;
String TAG = "NavigationViewListener";
Logger.init(TAG);
Fragment fragment = null;
switch (item.getItemId()){
case R.id.nav_home:
fragment = new FragmentHome();
fragmentTransaction = true;
break;
case R.id.nav_map:
fragment = new FragmentMap();
fragmentTransaction = true;
break;
case R.id.nav_log_out:
Logger.d("Pulsada opnción de LogOut");
break;
}
if(fragmentTransaction){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
item.setChecked(true);
getSupportActionBar().setTitle(item.getTitle());
}
}
}
Upvotes: 1
Views: 2094
Reputation: 19427
You could just pass the instance of your FragmentActivity
to NavigationListener
as a constructor param:
public class NavigationListener implements NavigationView.OnNavigationItemSelectedListener {
FragmentActivity activity;
public NavigationListener(FragmentActivity activity) {
this.activity = activity;
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// ...
if(fragmentTransaction){
activity.getSupportFragmentManager().beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
// ...
}
}
}
From your FragmentActivity
:
navigationView.setNavigationItemSelectedListener(new NavigationListener(this));
Upvotes: 1