I have a question regarding the passing of variables to my Fragment from the MainActivity.
In my MainActivity I have a button, which creates and displays a fragment respectively reloads it, if it is already created. (I am using this code to reload the fragment)
I am passing 2 double variables to it via the Bundle
-class. This works when I am first creating the fragment, but how can I update the variables, when I want to reload the fragment? In my code, I am not creating a new Fragment, but detach and reattach it. Is this possible with my approach or do I need something completely different?
MainActivity
public void loadWeatherFragment(){
longitude = this.getLongitude();
latitude = this.getLatitude();
FragmentManager fm = getFragmentManager();
Fragment currentFragment = this.getFragmentManager().findFragmentById(R.id.fragment_container);
//If the fragment already exists, reload it
if (currentFragment instanceof FragmentWeather) {
FragmentTransaction fragTransaction = this.getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
}
//Else create the fragment
else{
FragmentWeather mFragmentWeather = new FragmentWeather();
Bundle args = new Bundle();
args.putDouble("longitude", longitude);
args.putDouble("latitude", latitude);
mFragmentWeather.setArguments(args);
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container, mFragmentWeather);
ft.commit();
}
}
FragmentWeather
public class FragmentWeather extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_weather, container, false);
Double latitude = this.getArguments().getDouble("latitude");
Double longitude = this.getArguments().getDouble("longitude");
}
}