[英]How can i listen for Fragment change in my Activity?
I have an Activity which based on intent opens Fragment1 or Fragment2.我有一个基于意图打开 Fragment1 或 Fragment2 的活动。
From the activity after some stuff are done if the user is in Fragment1 i replace the fragment to Fragment2 and that can be done even from the Fragment1 diretly.如果用户在 Fragment1 中完成某些事情后的活动,我将 Fragment2 替换为 Fragment2,甚至可以直接从 Fragment1 完成。
For each Fragment i have to change items in my BottomAppBar, till i'm in Activity i have no problems with it as i've made just a function which changes the bottomAppBar items based on value passed it in.对于每个 Fragment,我必须更改我的 BottomAppBar 中的项目,直到我处于 Activity 中,我对它没有任何问题,因为我只做了一个 function,它根据传入的值更改 bottomAppBar 项目。
The issue is when the .replace
is called directly from the fragment.问题是当
.replace
直接从片段中调用时。
So i tought if it was possible to set in anyway a 'FragmentListener' which listens for fragment change in my Activity and call that function from it..所以我坚持是否可以设置一个“FragmentListener”来监听我的Activity中的片段变化并从中调用function..
My function looks like this:我的 function 看起来像这样:
private fun changeBottomBar(corpo: Boolean = false) {
if (corpo) {
binding.bottomAppBar.navigationIcon = ContextCompat.getDrawable(
this,
R.drawable.ic_baseline_menu_24
)
binding.bottomAppBar.menu.findItem(R.id.filter).isVisible = false
binding.bottomSheetTestata.titleBottomSheet.text = "Modifica Documento"
bottomSheetTestataBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
binding.bottomAppBar.menu.findItem(R.id.testata).isVisible = tipo != "Etichette"
}else {
binding.bottomAppBar.navigationIcon = null
binding.bottomAppBar.menu?.findItem(R.id.testata)?.isVisible = false
binding.bottomAppBar.menu?.findItem(R.id.filter)?.isVisible = true
binding.bottomSheetTestata.titleBottomSheet.text = "Nuovo Documento"
clearTestata()
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
}
}
And i call it for every .replace
where if the Fragment is Fragment2 i pass to it corpo = true
我为每个
.replace
调用它,如果 Fragment 是 Fragment2 我传递给它corpo = true
You can use EventBus Open source library for subscribing and publishing events.您可以使用 EventBus 开源库来订阅和发布事件。
https://greenrobot.org/eventbus/ https://greenrobot.org/eventbus/
For Publishing Event发布活动
//In fragment
EventBus.getDefault().post(new MessageEvent());
For Subscribing Event in Activity对于 Activity 中的订阅事件
//In Activity
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
Define you custom model class for event为事件定义自定义 model class
public static class MessageEvent { /* Additional fields if needed */ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.