gpt4 book ai didi

java - 如何在外部 Java 监听器中访问 getSupportFragmentManager

转载 作者:行者123 更新时间:2023-11-30 01:15:50 25 4
gpt4 key购买 nike

我必须在主类中为 NavigationView 设置监听器。但是 main 将包含很多东西,我希望它尽可能“分离”。

所以我会在他们自己的 java 文件中做监听器,比如:

navigationView.setNavigationItemSelectedListener(new NavigationListener());

问题来了,我必须调用 getSupportFragmentManager ,但无法访问,所以,我想我需要做类似的事情:context.getSupportFragmentManager 来制作我的“工作”。

但我不知道如何获取上下文。

我怎样才能得到它?

监听类:

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());
}
}
}

最佳答案

您可以将 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));

关于java - 如何在外部 Java 监听器中访问 getSupportFragmentManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37877894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com