【发布时间】:2021-11-16 16:57:37
【问题描述】:
android导航组件重新加载片段,并在从片段导航回片段时再次观察可变数据,我尝试了单个观察监听器但没有任何反应继续重新加载并再次点击api
public class TermsFragment extends Fragment {
private TermsViewModel termsViewModel;
private FragmentTermsBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
termsViewModel = new ViewModelProvider(this).get(TermsViewModel.class);
termsViewModel.init(getContext());
binding = FragmentTermsBinding.inflate(inflater, container, false);
termsViewModel.terms.observe(getViewLifecycleOwner(), terms -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
binding.terms.setText(Html.fromHtml(terms.replaceAll("<img.+?>", ""), Html.FROM_HTML_MODE_COMPACT));
} else {
binding.terms.setText(Html.fromHtml(terms.replaceAll("<img.+?>", "")));
}
});
View root = binding.getRoot();
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
和我的视图模型类
public class TermsViewModel extends ViewModel implements Onresponse {
public MutableLiveData<String> terms;
Context context=null;
public TermsViewModel() {
terms = new MutableLiveData<>();
}
public void init(Context context){
this.context=context;
Map<String,Object> body=new HashMap<>();
body.put("st", Api.app_data);
body.put("id",1);
body.put("lg",Constant.langstr);
Constant.connect(context,Api.app_data,body,this::onResponse,false);
}
@Override
public void onResponse(String st, JSONObject object, int online) {
if(object!=null) {
try {
terms.setValue(object.getString("data"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
【问题讨论】:
-
添加您的代码。
-
也添加你的单曲
observer -
@Manohar 更新
-
永远不要在 viewModel 中存储任何上下文/视图,这会导致内存泄漏。
-
onCreateView 会在你每次回到 fragment 时被调用。您需要检查 viewmodel 是否已经有 data/not 。如果它有数据,则将数据设置为 Ui,否则从服务器获取数据。