我在 MainActivity 类中初始化的底部导航视图中有四个片段:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_simulation, R.id.navigation_news, R.id.navigation_settings)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
}
}
我希望能够在设置片段中打开或关闭开关,并且主要在 HomeFragment 和 SimulationFragment 中具有此效果方面,在 HomeFragment 类的 OnCreateView 中,我为设置类创建了一个视图,以便可以在 HomeFragment 中找到:
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
Retrofit retrofitClient = RetrofitClient.getInstance();
service = retrofitClient.create(Service.class);
settings = inflater.inflate(R.layout.fragment_settings, container, false);
mapView = inflater.inflate(R.layout.fragment_home, container, false);
return mapView;
}
但是,例如,当我从 HomeFragment(作为导航主机片段)转到 SettingsFragment,检查一个 Switch 然后导航回 HomeFragment 时,状态似乎丢失了,这是我的基本思想正在尝试在 HomeFragment 中做:
Switch heatmap = settings.findViewById(R.id.displayHeatmap);
heatmap.setOnCheckedChangeListener((buttonView, isChecked) -> {
if(isChecked) {
addHeatMap();
}
else {
mMap.clear();
}
});