繁体   English   中英

安卓导航组件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM