[英]Android navigation component
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();
}
}
}
}
当您来回导航时,视图不会存在,但片段会存在。 因此,您可以将任何初始化代码移动到onCreate
而不是onCreateView
。 onCreate
每个片段的生命周期调用一次。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
termsViewModel = new ViewModelProvider(this).get(TermsViewModel.class);
termsViewModel.init(getContext());
}
这样你将:
init
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.