【问题标题】:How to change bottom app bar navigation icon programmatically如何以编程方式更改底部应用栏导航图标
【发布时间】:2019-01-26 17:36:17
【问题描述】:

我正在制作一个具有一个活动和许多片段的 Android 应用程序。该活动包含一个底部应用栏,该底部栏有一个导航图标。像这样:

  <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottom_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:backgroundTint="@color/colorbottomappbar"
        app:fabAlignmentMode="center"
        app:navigationIcon="@drawable/ic_menu_green_24dp">

    </com.google.android.material.bottomappbar.BottomAppBar>

此导航菜单图标将显示在每个片段中。但是,在某些片段中,我想将底部应用栏中的导航图标更改为后退按钮/图标。我怎样才能做到这一点?另外,目前我在主要活动中处理导航图标单击。在后退图标的情况下如何处理点击?它如何知道当前的片段是什么,我如何确定后退图标指向哪个片段?

【问题讨论】:

    标签: android


    【解决方案1】:

    如果您查看documentation,您会看到BottomAppBar 扩展自Toolbar,并且它有一个名为setNavigationIcon(int res) 的继承方法。

    您可以像这样实现主 Activity 实现的接口:

    interface FramentChangedListener {
         void onFragmentChanged(int type);
    }
    

    你的活动会做这样的事情:

    public class MainActivity extends Activity implements FragmentChangedListener {
        // This will keep track of what is currently shown
        private int current = 0;
    
        @Override
        public void onFragmentChanged(int type) {
            if (type == FirstFragment.SOME_TYPE) {
                // Update the current fragment value, we're associating each fragment 
                // with an int value.
                current = type;
    
                bottomAppBar.setNavigationIcon(R.drawable.your_back_icon);
            }
        }
        ...
    }
    

    在你的片段中,你会做这样的事情:

    public class FirstFragment extends Fragment {
        private FragmentChangedListener listener;
        public static final int SOME_TYPE = 1;
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if (context instanceOf FragmentChangedListener) {
                // context in this case is your activity, which implements FragmentChangedListener
                listener = (FragmentChangedListener) context;
    
                // You can call the listener now
                listener.onFragmentChanged(SOME_TYPE);
            }
        }
    }
    

    在您的 Activity 中,通过 setNavigationOnClickListener 向 BottomAppBar 添加一个侦听器,每当您收到导航图标事件时,您都可以检查我们定义的 current 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      相关资源
      最近更新 更多