Android 打开某些片段时如何隐藏/显示工具栏上的图标
我有几个片段和一个活动。应用程序包含始终可见的工具栏。我的工具栏上有一个图标。我需要在用户打开2,4,5个片段时隐藏这个图标,在用户打开1和3个片段时显示这个图标。我不需要此逻辑的所有代码,我需要建议如何实现它以及在何处为此行为添加一些逻辑假定您使用jetpack的导航和单个活动,则以下是正确的: 将目标更改侦听器添加到活动addOnDestinationChangedListener中的主导航控制器,接口为NavController.OnDestinationChangedListener。在侦听器内部,可以在onDestinationChanged实现中检查destination.id。实际上,你可以创建两个这样的集合Android 打开某些片段时如何隐藏/显示工具栏上的图标,android,kotlin,navigation,fragment,Android,Kotlin,Navigation,Fragment,我有几个片段和一个活动。应用程序包含始终可见的工具栏。我的工具栏上有一个图标。我需要在用户打开2,4,5个片段时隐藏这个图标,在用户打开1和3个片段时显示这个图标。我不需要此逻辑的所有代码,我需要建议如何实现它以及在何处为此行为添加一些逻辑假定您使用jetpack的导航和单个活动,则以下是正确的: 将目标更改侦听器添加到活动addOnDestinationChangedListener中的主导航控制器,接口为NavController.OnDestinationChangedListener。在
private val twoFourFiveDestinations =
setOf(R.id.two, R.id.four, R.id.five)
private val oneThreeDestinations =
setOf(R.id.one, R.id.three)
如果有四个5个Destination.ContainesDestination.id,只需进行这样的检查。。。并相应地管理图标的可见性,这将使生活更轻松
另一种解决方案是将图标管理移交给片段。您可以为comm和activity定义一些接口,并在各个片段启动并运行时管理工具栏图标。但是您需要在问题的每个片段中都这样做。如果您使用java,请创建一个伴随对象或静态变量
class Util {companion object { lateinit var toolbarImg: ImageView }}
在您的主要活动中,onCreate初始化工具栏和imageview
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
Util.toolbarImg = toolbar.findViewById(R.id.cartImg)
XML
步骤1:使用一种方法创建接口FragmentListener:
public interface MyFragmentListener {
void onChangeToolbarImage(boolean show);
}
步骤2:在活动中实施:
ImageView toolarImage= findViewById(R.id.toolbarimage)()///
@Override
public void onChangeToolbarImage(boolean show) {
if()
{ //check your imageView is Visible or not
toolbarImage.setVisibility(show); //change your ImageView's visibility
}
}
步骤3:在每个片段中,您需要从接口获取实例:
private MyFragmentListener fragmentListener;
步骤4:覆盖片段中的onAtach:
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MyFragmentListener)
fragmentListener = (MyFragmentListener) context;
fragmentListener.onChangeToolbarTitleImage(true or false);
}
private MyFragmentListener fragmentListener;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MyFragmentListener)
fragmentListener = (MyFragmentListener) context;
fragmentListener.onChangeToolbarTitleImage(true or false);
}