gpt4 book ai didi

java - 替换事务后如何保持 fragment 状态?

转载 作者:行者123 更新时间:2023-11-29 18:36:38 24 4
gpt4 key购买 nike

我在一个 Android 应用程序中有两个 fragment (假设是 FragmentAFragmentB),我使用 BottomBar 在它们之间切换。

我有一个正在使用 Retrofit 获取的数据列表,我正在使用 FragmentA 中的 RecyclerView 显示我有一个 <FragmentB 中的 strong>MapView。

我的问题是,每当我从 FragmentB 切换回 FragmentA 时,API 调用会再次获取数据列表。当我从 FragmentA 切换到 FragmentB 时,MapView 再次从头开始呈现。

有没有一种方法可以保持 FragmentA 的状态,即数据列表,直到我销毁 Activity 为止?并将 FragmentB 中的 MapView 保持原样?

我用下面的代码替换了一个 fragment 。

public void replaceFragment(Fragment fragment // This can be FragmentA or FragmentB) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.framelayout, fragment);
transaction.commit();
}

I just want to fragments to keep their state and not re-initialize every thing until the activity is destroyed. I guess that the life cycle methods of fragments play an important role here.

感谢任何帮助。谢谢!

最佳答案

Architecture components更适合您的场景。使用 LiveDataViewModel .

  1. 在 Activity 中,创建 View 模型并使用服务器响应更新实时数据。

  2. 在 fragment 中,使用实时数据更新 View 。

在这种情况下,ViewModel 生命周期附加到 Activity , fragment 事务不会影响存储的数据。由于您正在更新来自 LiveData 的数据,因此在创建 Activity 时只会进行一次 api 调用。除此之外,ViewModel 在方向更改后仍然存在,这意味着您的 LiveData 仍保留 API 响应。

关于java - 替换事务后如何保持 fragment 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54087731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com