【发布时间】:2020-05-19 08:32:51
【问题描述】:
我有几个片段和一个活动。该应用程序包含始终可见的工具栏。我的工具栏上有图标。我需要在用户打开 2、4、5 片段时隐藏此图标,并在用户打开 1 和 3 片段时显示此图标。我不需要这个逻辑的所有代码,我需要建议如何实现它以及在哪里为这个行为添加一些逻辑
【问题讨论】:
标签: android kotlin navigation fragment
我有几个片段和一个活动。该应用程序包含始终可见的工具栏。我的工具栏上有图标。我需要在用户打开 2、4、5 片段时隐藏此图标,并在用户打开 1 和 3 片段时显示此图标。我不需要这个逻辑的所有代码,我需要建议如何实现它以及在哪里为这个行为添加一些逻辑
【问题讨论】:
标签: android kotlin navigation fragment
假设您使用的是 jetpack 的导航和单个活动,以下情况为真:
将目标更改侦听器添加到活动中的主导航控制器(addOnDestinationChangedListener,接口为NavController.OnDestinationChangedListener)。在侦听器内部,您可以在 onDestinationChanged 实现中检查 destination.id。实际上,您可以像这样创建两个集合
private val twoFourFiveDestinations =
setOf(R.id.two, R.id.four, R.id.five)
private val oneThreeDestinations =
setOf(R.id.one, R.id.three)
只需像这样检查if(twoFourFiveDestinations.contains(destination.id) ... 并相应地管理您的图标可见性,这将使生活更轻松。
另一种解决方案是将图标管理交给片段。您可以定义一些与活动通信的接口,并在相应的片段启动并运行时管理工具栏图标。但是您需要在问题的每个片段中都这样做。
【讨论】:
第 1 步:使用一种方法创建接口 FragmentListener:
public interface MyFragmentListener {
void onChangeToolbarImage(boolean show);
}
第 2 步:在 YourActivity 中实施:
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 步:在 Fragment 中覆盖 onAtach:
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MyFragmentListener)
fragmentListener = (MyFragmentListener) context;
fragmentListener.onChangeToolbarTitleImage(true or false);
}
【讨论】:
如果您使用的是 java,请创建伴随对象或静态变量。
class Util {companion object { lateinit var toolbarImg: ImageView }}
在您的 Main Activity onCreate 中初始化您的工具栏和图像视图
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
Util.toolbarImg = toolbar.findViewById(R.id.cartImg)
XML
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<ImageView
android:id="@+id/cartImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:visibility="visible"
/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
现在您需要做的就是控制这个 ImageView 的可见性。 关于分片交易
隐藏
if(Util.toolbarImg.visibility == View.VISIBLE){
Util.toolbarImg.visibility = View.GONE }
【讨论】: