【问题标题】:Android navigation component安卓导航组件
【发布时间】: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,否则从服务器获取数据。

标签: java android


【解决方案1】:

当您来回导航时,视图无法保存,但片段可以。因此,您可以将任何初始化代码移动到onCreate 而不是onCreateViewonCreate 在每个片段的生命周期中调用一次。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
 
    termsViewModel = new ViewModelProvider(this).get(TermsViewModel.class);
    termsViewModel.init(getContext());
}

这样你会:

  • 只创建一次视图模型!至关重要的是,用新实例替换视图模型会丢弃您之前加载的所有数据;
  • 在此片段的生命周期中只调用一次init

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多