Bundle activity fragment 传递数据问题

记录开发过程中所遇问题

fragment复用,使用Bundle传值

activity中传值代码
for (Weather weather:weatherList){
    WeatherFragment weatherFragment=new WeatherFragment();
    Bundle bundle=new Bundle();
    bundle.putString("weather_text",weather.getWeatherText());
    Log.d(TAG, "initViewPager: "+weather.getWeatherText());
    weatherFragment.setArguments(bundle);
    fragmentList.add(weatherFragment);
}
MyFragmentPagerAdapter myFragmentPagerAdapter=new MyFragmentPagerAdapter(getSupportFragmentManager(),fragmentList);
myFragmentPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(myFragmentPagerAdapter);

fragment中接收值代码

public void onActivityCreated(@Nullable Bundle savedInstanceState) {
Bundle bundle=getArguments();
weatherText=bundle.getString("weather_text");
Log.d(TAG, "onActivityCreated: "+weatherText);

运行过程中改变activity中bundle所传递的值,结果fragment中所得值还是上一次的值,并没有根据activity中bundle的值的改变而改变

从logcat中可看到

07-26 14:22:32.625 28280-28280/com.coolweather.android D/WeatherActivity: initViewPager: {"aqiWeather":{"aqi":"53","pm25":"31"},"basicWeather":{"location":"天津","
    initViewPager: {"aqiWeather":{"aqi":"63","pm25":"45"},"basicWeather":{"location":"上海",


07-26 14:22:32.661 28280-28280/com.coolweather.android D/WeatherFragment: onActivityCreated: {"aqiWeather":{"aqi":"40","pm25":"8"},"basicWeather":{"location":"北京",
07-26 14:22:32.711 28280-28280/com.coolweather.android D/WeatherFragment: onActivityCreated: {"aqiWeather":{"aqi":"63","pm25":"45"},"basicWeather":{"location":"上海",

简单描述  activity中 北京->天津,然后刷新viewpager,到fragment中没有出现改变还是上一次传递的 北京

这个问题 关闭应用再重新打开应用 就能解决,也就是说重新跳转一下fragment所在activity就能解决;重新跳转后activity中bundle的改变就能传递到fragment中。希望找到一个不用跳转,完美刷新fragment内容的方法。

待日后寻找解决方法。

猜你喜欢

转载自blog.csdn.net/qq_36258441/article/details/81219271