簡體   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