Java 我如何倾听活动中的片段变化?
我有一个基于意图的活动打开了Fragment1或Fragment2 如果用户在Fragment1中,则在完成某些操作后的活动中,我将该片段替换为Fragment2,甚至可以直接从Fragment1执行该操作 对于每个片段,我必须更改BottomAppBar中的项,直到我进入活动,我对它没有任何问题,因为我只做了一个函数,根据传入的值更改BottomAppBar项 问题是直接从片段调用Java 我如何倾听活动中的片段变化?,java,android,kotlin,android-fragments,Java,Android,Kotlin,Android Fragments,我有一个基于意图的活动打开了Fragment1或Fragment2 如果用户在Fragment1中,则在完成某些操作后的活动中,我将该片段替换为Fragment2,甚至可以直接从Fragment1执行该操作 对于每个片段,我必须更改BottomAppBar中的项,直到我进入活动,我对它没有任何问题,因为我只做了一个函数,根据传入的值更改BottomAppBar项 问题是直接从片段调用.replace时 所以我想,是否有可能设置一个“FragmentListener”,监听我活动中的片段更改,并从
.replace
时
所以我想,是否有可能设置一个“FragmentListener”,监听我活动中的片段更改,并从中调用该函数
我的函数如下所示:
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
}
}
我为每个
.replace
调用它,如果片段是片段2,我将传递给它corpo=true
您可以使用EventBus开源库订阅和发布事件
用于发布事件
//In fragment
EventBus.getDefault().post(new MessageEvent());
用于订阅活动中的事件
//In Activity
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
为事件定义自定义模型类
public static class MessageEvent { /* Additional fields if needed */ }
嗨,Ranjeet,我会阻止使用外部librariesHi@NiceToMytyuk,然后使用接口在片段和活动之间侦听