【问题标题】:Stop fragment's functions and calls and reset inner variables停止片段的函数和调用并重置内部变量
【发布时间】:2020-06-07 04:45:51
【问题描述】:

在我的应用中,我有一个活动和一个片段。

片段与活动给出的参数“A”一起工作。它有自己的数组等。片段在不同的函数之间移动(从一个函数到另一个函数),它还调用异步函数来接收文件、从数据库读取等。

情况是,我想,在我按下 mi 活动中的按钮的具体时刻,从我的主要活动向片段发送通知以停止所有处理并从开始使用原始参数的过程开始“乙”。即重启fragment中的所有变量,停止当前运行的所有函数,以及所有异步函数等,以b参数启动fragment中的整个进程。

我的解决方案,不起作用如下:

  • 我在片段中有一个 GetRequest(request) 函数。

  • 在活动中,我调用了这个函数,修复了一个参数请求 == B。

  • 在片段的每个函数中,我在这些函数的开头都有一个条件,检查是否(请求!= null)。然后,如果 request != null 我在片段中调用一个函数来重新启动所有内部变量,并调用第一个函数等。否则,我继续正常的代码。

问题是我认为这不适用于异步函数,因为有时我会在变量中收到错误,我重置为 null 并且它们正在尝试读取,等等。

我确信这不是实现这一目标的最佳方式。你能帮帮我吗?

谢谢!

【问题讨论】:

  • 所以如果我理解正确,你想将参数 A 传递给片段,然后在片段中运行函数检查参数 A 的值?
  • 第一次运行带参数A的fragment在fragment中效果很好。问题是当我将参数 A 更改为 B 时。片段中运行了很多函数、用于接收文件(从数据库读取)、变量、数组的异步函数......我怎样才能重置所有这些东西并重新开始带有参数 B 的片段中的进程?

标签: java android android-studio android-fragments android-activity


【解决方案1】:

在这种情况下,我建议您使用LiveDataViewModel

例如:

首先创建一个ViewModel

YourViewModel.java:

//initialize this mutableLiveData first
public MutableLiveData<String> parameterA = new MutableLiveData<>("");

private void setParameterA(String myValue){
    parameterA.setValue(myValue);
}

然后在YourActivity.java中,获取ViewModel

YourViewModel viewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {

   ... all other thing 

   viewModel = ViewModelProviders.of(this).get(YourViewModel.class);
}


//then whatever the situation in activity,u want to update parameterA
private void SomeSituation() {
    //update the parameterA
    ...
    viewModel.setParameterA("Your value Here")
}

然后在你的片段中,观察parameterA的值

你的片段:

  // in onCreate() or onViewCreated()

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState); 

  //get the same viewModel
  viewModel = ViewModelProviders.of(requireActivity()).get(YourViewModel.class);


  viewModel.parameterA.observe(getViewLifecycleOwner(), new Observer<String>() {
        @Override
        public void onChanged(String parameterA) {
            // anything changes on parameterA
            // do whatever you want with the value S
        }
    });
 }

所以通过上面的方法,只要有parameterA在activity中的变化,fragment就会异步更新,那么你可以对onChanged()部分里面的更新值做任何你想做的事情。

正如你在评论中提到的:

接收文件(从数据库读取)、变量、数组

LiveData 也可以用于自定义模型类,例如MutableLiveData&lt;List&lt;Post&gt;&gt;,所以当您在activitysetValue() 时,您的片段可以在onChanged() 中获取值asynchornous。

在使用LiveData之前,你需要Add Components to your Project

这是Android MVVM架构,可以看文档here,,example here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 2014-02-01
    • 2018-10-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多