Android Studio: 帮助... LiveData在不同的片段中保持不同的值
创始人
2024-08-17 01:00:08
0

要实现在不同的片段中保持不同的 LiveData 值的功能,可以通过使用 ViewModel 来实现。

首先,创建一个继承自 ViewModel 的类,用于保存 LiveData 的值。例如:

class MyViewModel : ViewModel() {
    val liveData1 = MutableLiveData()
    val liveData2 = MutableLiveData()
}

在每个片段中,通过获取共享的 ViewModel 实例来访问 LiveData 的值。例如:

class Fragment1 : Fragment() {
    private val viewModel: MyViewModel by activityViewModels()

    // 在此片段中使用 liveData1
    // ...
}

class Fragment2 : Fragment() {
    private val viewModel: MyViewModel by activityViewModels()

    // 在此片段中使用 liveData2
    // ...
}

在每个片段中,可以通过监听 LiveData 的变化来更新 UI。例如:

class Fragment1 : Fragment() {
    private val viewModel: MyViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel.liveData1.observe(viewLifecycleOwner, { value ->
            // 当 liveData1 的值发生变化时,更新 UI
            // ...
        })
    }
}

在 Activity 中,使用 ViewModelProvider 来创建和获取 ViewModel 实例。例如:

class MainActivity : AppCompatActivity() {
    private lateinit var viewModel: MyViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
    }
}

通过这种方式,不同的片段可以独立地设置和获取 LiveData 的值,而不会相互影响。

相关内容

热门资讯

关于透视!wepoker手机助... 关于透视!wepoker手机助手,pokemmo辅助脚本,窍门教程(有挂头条)-哔哩哔哩;1、wep...
关于透视!wepoker可以透... 关于透视!wepoker可以透视码,wepoker怎么买辅助,演示教程(有挂神器)-哔哩哔哩1、we...
曝光透视!pokemmo脚本辅... 曝光透视!pokemmo脚本辅助下载,we poker辅助器v3.3,教材教程(真的有挂)-哔哩哔哩...
详细透视!wepoker钻石怎... 详细透视!wepoker钻石怎么看底牌,德普之星透视辅助软件激活码,烘培教程(存在有挂)-哔哩哔哩1...
揭幕透视!拱趴大菠萝有挂吗,w... 揭幕透视!拱趴大菠萝有挂吗,wepoker提高好牌率,手册教程(新版有挂)-哔哩哔哩1、下载好拱趴大...
分享透视!佛手在线有挂吗,we... 分享透视!佛手在线有挂吗,wepoker透视破解版,教程书教程(今日头条)-哔哩哔哩1、进入游戏-大...
曝光透视!wepoker国外版... 曝光透视!wepoker国外版透视,wpk系统是否存在作必弊行为,指引教程(发现有挂)-哔哩哔哩wp...
了解透视!竞技联盟破解版最新版... 了解透视!竞技联盟破解版最新版,wepoker私局辅助,学习教程(果真有挂)-哔哩哔哩运竞技联盟破解...
普及透视!hhpoker免费透... 普及透视!hhpoker免费透视脚本,wpk透视怎么安装,模块教程(有挂秘诀)-哔哩哔哩所有人都在同...
关于透视!wejoker手机版... 关于透视!wejoker手机版透视脚本,拱趴游戏破解器,技法教程(有挂技术)-哔哩哔哩关于透视!we...