我必须在我的主类中为NavigationView
设置监听器。但主要的,将包含很多东西,我想让它最“分离”。
所以我会在他们自己的java文件中做听众,比如:
navigationView.setNavigationItemSelectedListener(new NavigationListener());
问题来了,我必须打电话给getSupportFragmentManager
,但是不可访问,所以,我想我需要做一些像context.getSupportFragmentManager
这样的事情来让“工作”。
但我不知道如何获得背景。
我怎样才能得到它?
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());
}
}
}
答案 0 :(得分:1)
您可以将FragmentActivity
的实例作为构造函数参数传递给NavigationListener
:
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();
// ...
}
}
}
来自FragmentActivity
:
navigationView.setNavigationItemSelectedListener(new NavigationListener(this));