Android Fragment中LiveData仅在屏幕旋转或配置变更后更新的问题求助
Android Fragment中LiveData仅在屏幕旋转或配置变更后更新的问题求助
我正在开发一款Android天气应用,功能是从API拉取数据并展示。目前用了WeatherViewModel和LiveData来处理配置变更时的数据保留,以及在WeatherFragment中展示数据,但遇到了一个头疼的问题:Fragment里的TextView只有在屏幕旋转或者其他配置变更后,才会更新显示天气数据。
具体来说,当我点击“Fetch Weather”按钮时,明明已经触发了数据拉取,但TextView一直是空白状态,必须等我旋转屏幕或者触发配置变更,数据才会突然显示出来。我想要的是点击按钮后立刻就能看到更新后的天气信息,而不是等配置变更。
代码结构
WeatherFragment.java
在这个Fragment里,我初始化了WeatherViewModel,并在onViewCreated中观察getWeatherData()。点击按钮时,会调用weatherViewModel.fetchWeatherData(city)来根据用户输入拉取数据。
public class WeatherFragment extends Fragment { private WeatherViewModel weatherViewModel; private FragmentWeatherBinding binding; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = FragmentWeatherBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); weatherViewModel = new ViewModelProvider(this).get(WeatherViewModel.class); binding.buttonFetchWeather.setOnClickListener(v -> { String city = binding.editTextCity.getText().toString().trim(); if (!city.isEmpty()) { weatherViewModel.fetchWeatherData(city); // Retrieve weather data for the city } else { binding.textViewWeather.setText("Please enter a city name."); } }); weatherViewModel.getWeatherData().observe(getViewLifecycleOwner(), weatherData -> { if (weatherData != null) { binding.textViewWeather.setText(weatherData); } }); } @Override public void onDestroyView() { super.onDestroyView(); binding = null; // Avoid memory leaks } }
WeatherViewModel.java
在ViewModel里,fetchWeatherData(city)会触发API请求,并把结果存入MutableLiveData中。
package com.example.weather; import android.util.Log; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class WeatherViewModel extends ViewModel { private final WeatherRepository repository; private MutableLiveData<String> weatherResult = new MutableLiveData<>(); public WeatherViewModel() { repository = new WeatherRepository(); } public void fetchWeatherData(String city) { weatherResult = repository.getWeather(city); } public LiveData<String> getWeather() { return weatherResult; } }
我已经尝试过的操作
我把getWeatherData()的观察者从onViewCreated移到了onCreateView里,但问题依然存在,没有任何改善。
我的疑问
- 为什么LiveData只有在配置变更后才会触发更新?
- 如何让TextView在点击按钮后立刻更新显示数据?
- 这个问题是不是和
fetchWeatherData(city)里的异步行为有关?如果是的话,该怎么调整才能让它触发即时更新?
真心希望能得到大家的帮助和建议,谢谢各位了!
备注:内容来源于stack exchange,提问作者Shai Ben Hemo
相关产品推荐
相关产品推荐

