【问题标题】:Android new Bottom Navigation bar or BottomNavigationViewAndroid新的底部导航栏或BottomNavigationView
【发布时间】:2016-07-02 03:01:51
【问题描述】:

看到新指南出来了,并在google photos 最新的应用程序中使用。 不知道如何使用新的底部导航栏。 翻翻新的支持库,没找到线索。

找不到任何官方样本。

如何使用新的底栏?不想做任何定制。

【问题讨论】:

标签: android bottomnavigationview


【解决方案1】:

我想你可能会找这个。

这里有一个快速的 sn-p 入门:

public class MainActivity extends AppCompatActivity {
    private BottomBar mBottomBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Notice how you don't use the setContentView method here! Just
        // pass your layout to bottom bar, it will be taken care of.
        // Everything will be just like you're used to.
        mBottomBar = BottomBar.bind(this, R.layout.activity_main,
                savedInstanceState);

        mBottomBar.setItems(
                new BottomBarTab(R.drawable.ic_recents, "Recents"),
                new BottomBarTab(R.drawable.ic_favorites, "Favorites"),
                new BottomBarTab(R.drawable.ic_nearby, "Nearby"),
                new BottomBarTab(R.drawable.ic_friends, "Friends")
        );

        mBottomBar.setOnItemSelectedListener(new OnTabSelectedListener() {
            @Override
            public void onItemSelected(final int position) {
                // the user selected a new tab
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mBottomBar.onSaveInstanceState(outState);
    }
}

这是参考链接。

https://github.com/roughike/BottomBar

编辑新版本。

底部导航视图在材料设计指南中已有一段时间了,但将其实现到我们的应用中并不容易。一些应用程序已经构建了自己的解决方案,而其他应用程序则依赖第三方开源库来完成工作。现在设计支持库看到添加了这个底部导航栏,让我们深入了解如何使用它!

如何使用?

首先我们需要更新我们的依赖!

compile ‘com.android.support:design:25.0.0’

设计 xml。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Content Container -->

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/bottom_navigation_main" />

</RelativeLayout>

根据您的要求创建菜单。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_favorites"
        android:enabled="true"
        android:icon="@drawable/ic_favorite_white_24dp"
        android:title="@string/text_favorites"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_schedules"
        android:enabled="true"
        android:icon="@drawable/ic_access_time_white_24dp"
        android:title="@string/text_schedules"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_music"
        android:enabled="true"
        android:icon="@drawable/ic_audiotrack_white_24dp"
        android:title="@string/text_music"
        app:showAsAction="ifRoom" />
</menu>

处理启用/禁用状态。制作选择器文件。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
      android:state_checked="true"
      android:color="@color/colorPrimary" />
  <item
      android:state_checked="false"
      android:color="@color/grey" />
 </selector>

处理点击事件。

BottomNavigationView bottomNavigationView = (BottomNavigationView)
                findViewById(R.id.bottom_navigation);
        
bottomNavigationView.setOnNavigationItemSelectedListener(
        new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_favorites:
                        
                        break;
                    case R.id.action_schedules:
                    
                        break;
                    case R.id.action_music:
                    
                        break;
                }
                return false;
            }
});

编辑:使用 Androidx 你只需要添加以下依赖项。

implementation 'com.google.android.material:material:1.2.0-alpha01'

布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto" 
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent">
    <com.google.android.material.bottomnavigation.BottomNavigationView
            android:layout_gravity="bottom"
            app:menu="@menu/bottom_navigation_menu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</FrameLayout>

如果你想了解更多关于它的方法和它的工作原理read this.

肯定会对你有所帮助。

【讨论】:

  • 示例中的底部栏仍然由您自己自定义,任何方式使用原始android lib。我认为它可能在支持库中。还是还没公开?
  • @zjywill 它不是自定义的,但它是在我们的应用程序中使用官方底部导航栏功能的方式。试试这个代码。
  • 我不建议您使用粗略的底栏,因为 API 没有完全实现并且我遇到了渲染问题。您无法在运行时更改图标,并且它一直忽略我为按钮背景设置的颜色。
  • 请回答如何保存历史记录
  • mShiftingMode 上的 java 反射帮助了我!不公开这个字段我不知道他们在想什么
【解决方案2】:

您应该使用 v25 Android 支持库中的 BottomNavigationView。 它代表了一个标准的应用底部导航栏。

这是一篇关于 Medium 的帖子,其中有一个分步指南: https://medium.com/@hitherejoe/exploring-the-android-design-support-library-bottom-navigation-drawer-548de699e8e0#.9vmiekxze

【讨论】:

  • stackoverflow.com/questions/40153888/… hello maxim.. 我实现了这个,但它没有出现..
  • @SagarChavada 你可能想看看这个post
  • @DroidDev 这是因为在发布此答案的当天发布了 BottomNavigationView。在此之前,只有第三方解决方案可用。
  • 你知道是否可以使用适配器来自定义视图吗?
  • @Alan,看起来 BottomNavigationView 是支持库的一部分,支持的 API 级别最低为 9,所以我想它会起作用。您仍然可以在模拟器上进行检查以 100% 确定。
【解决方案3】:

我原来的答案是BottomNavigationView,但现在有一个BottomAppBar。我在顶部添加了一个带有实现链接的部分。

底部应用栏

BottomAppBar 支持浮动操作按钮。

图片来自here。有关设置 BottomAppBar 的帮助,请参阅 documentationthis tutorial

底部导航视图

以下完整示例显示了如何制作与问题中的图像相似的底部导航视图。另请参阅文档中的Bottom Navigation

添加设计支持库

将此行添加到您应用的 build.grade 文件中,旁边是其他支持库。

implementation 'com.android.support:design:28.0.0'

将版本号替换为当前版本。

创建活动布局

我们添加到布局中的唯一特别的东西是BottomNavigationView。要在单击时更改图标和文本的颜色,可以使用selector 而不是直接指定颜色。为简单起见,此处省略。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_nav_menu"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white" />

</RelativeLayout>

请注意,我们使用layout_alignParentBottom 将其实际放在底部。

定义菜单项

上面用于底部导航视图的 xml 引用了 bottom_nav_menu。这就是我们视图中定义每个项目的内容。我们现在就做。您所要做的就是add a menu resource,就像操作栏或工具栏一样。

bottom_nav_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_recents"
        android:enabled="true"
        android:icon="@drawable/ic_action_recents"
        android:title="Recents"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_favorites"
        android:enabled="true"
        android:icon="@drawable/ic_action_favorites"
        android:title="Favorites"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_nearby"
        android:enabled="true"
        android:icon="@drawable/ic_action_nearby"
        android:title="Nearby"
        app:showAsAction="ifRoom" />
</menu>

您需要将适当的图标添加到您的项目中。如果您转到 File > New > Image Asset 并选择 Action Bar and Tab Icons 作为 Icon Type,这并不难。

添加项目选择监听器

这里没有什么特别的事情发生。我们只需在 Activity 的 onCreate 方法中为底部导航栏添加一个侦听器。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_recents:
                        Toast.makeText(MainActivity.this, "Recents", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_favorites:
                        Toast.makeText(MainActivity.this, "Favorites", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_nearby:
                        Toast.makeText(MainActivity.this, "Nearby", Toast.LENGTH_SHORT).show();
                        break;

                }
                return true;
            }
        });
    }
}

需要更多帮助?

我通过观看以下 YouTube 视频学会了如何做到这一点。电脑声音有点奇怪,但是演示很清晰。

【讨论】:

    【解决方案4】:

    您还可以使用带有自定义选项卡视图的选项卡布局来实现此目的。

    custom_tab.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?attr/selectableItemBackground"
        android:gravity="center"
        android:orientation="vertical"
        android:paddingBottom="10dp"
        android:paddingTop="8dp">
    
        <ImageView
            android:id="@+id/icon"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:scaleType="centerInside"
            android:src="@drawable/ic_recents_selector" />
    
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:textAllCaps="false"
            android:textColor="@color/tab_color"
            android:textSize="12sp"/>
    </LinearLayout>
    

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <android.support.v4.view.ViewPager
    
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            style="@style/AppTabLayout"
            android:layout_width="match_parent"
            android:layout_height="56dp"
            android:background="?attr/colorPrimary" />
    
    </LinearLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        private TabLayout mTabLayout;
    
        private int[] mTabsIcons = {
                R.drawable.ic_recents_selector,
                R.drawable.ic_favorite_selector,
                R.drawable.ic_place_selector};
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Setup the viewPager
            ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
            MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
            viewPager.setAdapter(pagerAdapter);
    
            mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
            mTabLayout.setupWithViewPager(viewPager);
    
            for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                TabLayout.Tab tab = mTabLayout.getTabAt(i);
                tab.setCustomView(pagerAdapter.getTabView(i));
            }
    
            mTabLayout.getTabAt(0).getCustomView().setSelected(true);
        }
    
    
        private class MyPagerAdapter extends FragmentPagerAdapter {
    
            public final int PAGE_COUNT = 3;
    
            private final String[] mTabsTitle = {"Recents", "Favorites", "Nearby"};
    
            public MyPagerAdapter(FragmentManager fm) {
                super(fm);
            }
    
            public View getTabView(int position) {
                // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
                TextView title = (TextView) view.findViewById(R.id.title);
                title.setText(mTabsTitle[position]);
                ImageView icon = (ImageView) view.findViewById(R.id.icon);
                icon.setImageResource(mTabsIcons[position]);
                return view;
            }
    
            @Override
            public Fragment getItem(int pos) {
                switch (pos) {
    
                    case 0:
                        return PageFragment.newInstance(1);
    
                    case 1:
                        return PageFragment.newInstance(2);
                    case 2:
                        return PageFragment.newInstance(3);
    
                }
                return null;
            }
    
            @Override
            public int getCount() {
                return PAGE_COUNT;
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                return mTabsTitle[position];
            }
        }
    
    }
    

    Download Complete Sample Project

    【讨论】:

    • 根据 Google 设计指南,不应使用滑动动作在选项卡之间切换。 google.com/design/spec/components/…
    • 如果您将功劳归功于写下这些行为的作者,那就太好了:)
    【解决方案5】:

    Google 在设计支持库的 25.0.0 版本之后推出了 BottomNavigationView。但它有以下限制:

    1. 您不能删除标题和中心图标。
    2. 您无法更改标题文本大小。
    3. 您不容改变背景颜色它总是̶c̶o̶l̶o̶r̶P̶r̶i̶m̶a̶r̶y̶.̶强> LI>
    4. 它没有 BottomNavigationBehavior:因此没有通过 CordinatorLayout 与 FAB 或 SnackBar 集成。
    5. 每个 menuItem 都是 FrameLayout 的纯扩展,因此没有任何漂亮的圆形显示效果

    因此,您可以使用第一个版本的 BottomNavigationView 做的最大事情是:(无需任何反射或自行实现库)。

    所以,如果你想要这些。您可以使用像roughike/BottomBar 这样的第三方库或自己实现该库。

    【讨论】:

    • 仅供记录,您可以更改背景颜色,也可以更改标题文本大小(但我发现我使用的方法存在其他问题)。使用 android:background="xxx" 会改变它的背景颜色,但是如果你还指定了一个app:itemBackground="xxx",那么所有的项目都共享这个颜色并且你看不到背景(除非你添加了透明度,但是所有的图标仍然共享颜色相同)。 Android 团队发布了如此糟糕的组件非常糟糕……总是 75% 完成,错过了让它变得更好的额外努力。
    • 我们可以改变背景颜色
    • 嗨,我正在使用相同的库并且它工作正常,但在这里我只想在底部栏的中心显示没有标题的图标。可能吗?我已经尝试在菜单项中放空,但图标仍然只显示在顶部。如何在底部栏的中心只显示没有标题的图标?
    • 嗨,请在这里查看我的答案stackoverflow.com/questions/40183239/…
    • @MartinMarconcini 您是如何更改底部导航视图的文本大小的?
    【解决方案6】:

    正如 Sanf0rd 提到的,Google 推出了 BottomNavigationView,作为 Design Support Library 25.0.0 版的一部分。他提到的限制大多是正确的,除了您可以更改视图的背景颜色,甚至是文本颜色和图标色调颜色。当您添加超过 4 个项目时,它还有一个动画(遗憾的是它无法手动启用或禁用)。

    我写了一个详细的教程,其中包含示例和随附的存储库,您可以在此处阅读: https://blog.autsoft.hu/now-you-can-use-the-bottom-navigation-view-in-the-design-support-library/


    它的要点

    您必须在您的应用级别中添加这些build.gradle

    compile 'com.android.support:appcompat-v7:25.0.0'  
    compile 'com.android.support:design:25.0.0'
    

    你可以像这样将它包含在你的布局中:

    <android.support.design.widget.BottomNavigationView  
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/bottom_navigation_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:itemBackground="@color/darkGrey"
            app:itemIconTint="@color/bottom_navigation_item_background_colors"
            app:itemTextColor="@color/bottom_navigation_item_background_colors"
            app:menu="@menu/menu_bottom_navigation" />
    

    您可以通过这样的菜单资源指定项目:

    <?xml version="1.0" encoding="utf-8"?>  
    <menu  
        xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/action_one"
            android:icon="@android:drawable/ic_dialog_map"
            android:title="One"/>
        <item
            android:id="@+id/action_two"
            android:icon="@android:drawable/ic_dialog_info"
            android:title="Two"/>
        <item
            android:id="@+id/action_three"
            android:icon="@android:drawable/ic_dialog_email"
            android:title="Three"/>
        <item
            android:id="@+id/action_four"
            android:icon="@android:drawable/ic_popup_reminder"
            android:title="Four"/>
    </menu>
    

    并且你可以将色调和文本颜色设置为颜色列表,这样当前选中的项目就会被高亮显示:

    <?xml version="1.0" encoding="utf-8"?>  
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item
            android:color="@color/colorAccent"
            android:state_checked="false"/>
        <item
            android:color="@android:color/white"
            android:state_checked="true"/>
    
    </selector>
    

    最后,您可以使用 OnNavigationItemSelectedListener 处理项目的选择:

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {  
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment fragment = null;
            switch (item.getItemId()) {
                case R.id.action_one:
                    // Switch to page one
                    break;
                case R.id.action_two:
                    // Switch to page two
                    break;
                case R.id.action_three:
                    // Switch to page three
                    break;
            }
            return true;
        }
    });
    

    【讨论】:

    • 太棒了!建议 - 删除 app:itemBackground="@color/darkGrey" 以实现原生圆形波纹效果。
    【解决方案7】:

    您可以尝试其他备用库:- https://github.com/Ashok-Varma/BottomNavigation

    <com.ashokvarma.bottomnavigation.BottomNavigationBar
        android:layout_gravity="bottom"
        android:id="@+id/bottom_navigation_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    
    BottomNavigationBar bottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
    
    bottomNavigationBar
                    .addItem(new BottomNavigationItem(R.drawable.ic_home_white_24dp, "Home"))
                    .addItem(new BottomNavigationItem(R.drawable.ic_book_white_24dp, "Books"))
                    .addItem(new BottomNavigationItem(R.drawable.ic_music_note_white_24dp, "Music"))
                    .addItem(new BottomNavigationItem(R.drawable.ic_tv_white_24dp, "Movies & TV"))
                    .addItem(new BottomNavigationItem(R.drawable.ic_videogame_asset_white_24dp, "Games"))
                    .initialise();
    

    【讨论】:

    【解决方案8】:

    我创建了一个使用 gridview 和菜单资源的私有类:

    private class BottomBar {
    
        private GridView mGridView;
        private Menu     mMenu;
        private BottomBarAdapter mBottomBarAdapter;
        private View.OnClickListener mOnClickListener;
    
        public BottomBar (@IdRes int gridviewId, @MenuRes int menuRes,View.OnClickListener onClickListener) {
            this.mGridView = (GridView) findViewById(gridviewId);
            this.mMenu = getMenu(menuRes);
            this.mOnClickListener = onClickListener;
    
            this.mBottomBarAdapter = new BottomBarAdapter();
            this.mGridView.setAdapter(mBottomBarAdapter);
        }
    
        private Menu getMenu(@MenuRes int menuId) {
            PopupMenu p = new PopupMenu(MainActivity.this,null);
            Menu menu = p.getMenu();
            getMenuInflater().inflate(menuId,menu);
            return menu;
        }
    
        public GridView getGridView(){
            return mGridView;
        }
    
        public void show() {
            mGridView.setVisibility(View.VISIBLE);
            mGridView.animate().translationY(0);
        }
    
        public void hide() {
            mGridView.animate().translationY(mGridView.getHeight());
        }
    
    
    
        private class BottomBarAdapter extends BaseAdapter {
    
            private LayoutInflater    mInflater;
    
            public BottomBarAdapter(){
                this.mInflater = LayoutInflater.from(MainActivity.this);
            }
    
            @Override
            public int getCount() {
                return mMenu.size();
            }
    
            @Override
            public Object getItem(int i) {
                return mMenu.getItem(i);
            }
    
            @Override
            public long getItemId(int i) {
                return 0;
            }
    
            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
    
                MenuItem item = (MenuItem) getItem(i);
    
                if (view==null){
                    view = mInflater.inflate(R.layout.your_item_layout,null);
                    view.setId(item.getItemId());
                }
    
                view.setOnClickListener(mOnClickListener);
                view.findViewById(R.id.bottomnav_icon).setBackground(item.getIcon());
                ((TextView) view.findViewById(R.id.bottomnav_label)).setText(item.getTitle());
    
                return view;
            }
        }
    

    your_menu.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:id="@+id/item1_id"
            android:icon="@drawable/ic_item1"
            android:title="@string/title_item1"/>
        <item android:id="@+id/item2_id"
            android:icon="@drawable/ic_item2"
            android:title="@string/title_item2"/>
        ...
    </menu>
    

    还有一个自定义布局项 your_item_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="16dp">
        <ImageButton android:id="@+id/bottomnav_icon"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_gravity="top|center_horizontal"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="4dp"/>
        <TextView android:id="@+id/bottomnav_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center_horizontal"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="4dp"
            style="@style/mystyle_label" />
    </LinearLayout>
    

    在你的 mainactivity 中使用:

    BottomBar bottomBar = new BottomBar(R.id.YourGridView,R.menu.your_menu, mOnClickListener);
    

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.item1_id:
                    //todo item1
                    break;
                case R.id.item2_id:
                    //todo item2
                    break;
                ...
            }
        }
    }
    

    在 layout_activity.xml 中

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
        ...
        <FrameLayout android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
    
        <GridView android:id="@+id/bottomNav"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/your_background_color"
            android:verticalSpacing="0dp"
            android:horizontalSpacing="0dp"
            android:numColumns="4"
            android:stretchMode="columnWidth"
            app:layout_anchor="@id/fragment_container"
            app:layout_anchorGravity="bottom"/>
    </android.support.design.widget.CoordinatorLayout>
    

    【讨论】:

      【解决方案9】:

      我认为这也很有用。

      片段

      public class MainActivity : AppCompatActivity, BottomNavigationBar.Listeners.IOnTabSelectedListener
      {
          private BottomBar _bottomBar;
      
          protected override void OnCreate(Bundle bundle)
          {
              base.OnCreate(bundle);
      
              SetContentView(Resource.Layout.MainActivity);
      
              _bottomBar = BottomBar.Attach(this, bundle);
              _bottomBar.SetItems(
                  new BottomBarTab(Resource.Drawable.ic_recents, "Recents"),
                  new BottomBarTab(Resource.Drawable.ic_favorites, "Favorites"),
                  new BottomBarTab(Resource.Drawable.ic_nearby, "Nearby")
              );
              _bottomBar.SetOnItemSelectedListener(this);
              _bottomBar.HideShadow();
              _bottomBar.UseDarkTheme(true);
              _bottomBar.SetTypeFace("Roboto-Regular.ttf");
      
              var badge = _bottomBar.MakeBadgeForTabAt(1, Color.ParseColor("#f02d4c"), 1);
              badge.AutoShowAfterUnSelection = true;
          }
      
          public void OnItemSelected(int position)
          {
      
          }
      
          protected override void OnSaveInstanceState(Bundle outState)
          {
              base.OnSaveInstanceState(outState);
      
              // Necessary to restore the BottomBar's state, otherwise we would
              // lose the current tab on orientation change.
              _bottomBar.OnSaveInstanceState(outState);
          }
      }
      

      链接

      https://github.com/pocheshire/BottomNavigationBar

      它是为 Xamarin 开发人员移植到 C# 的 https://github.com/roughike/BottomBar

      【讨论】:

        【解决方案10】:

        Design Support Library 25版中新增了官方BottomNavigationView

        https://developer.android.com/reference/android/support/design/widget/BottomNavigationView.html 加入gradle compile 'com.android.support:design:25.0.0'

        XML

        <android.support.design.widget.BottomNavigationView
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:design="http://schema.android.com/apk/res/android.support.design"
            android:id="@+id/navigation"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            design:menu="@menu/my_navigation_items" />
        

        【讨论】:

          【解决方案11】:

          这个库 BottomNavigationViewEx 扩展了 Google 的 BottomNavigationView。您可以轻松自定义 Google 的库,使其底部导航栏按您希望的方式显示。您可以禁用移动模式、更改图标和文本的可见性等等。一定要试一试。

          【讨论】:

            【解决方案12】:

            我已经提到了这个github post,并在底部标签栏中为three fragment 页面设置了three layouts

            FourButtonsActivity.java:

            bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
                        new BottomBarFragment(LibraryFragment.newInstance(R.layout.library_fragment_layout), R.drawable.ic_update_white_24dp, "Recents"),
                        new BottomBarFragment(PhotoEffectFragment.newInstance(R.layout.photo_effect_fragment), R.drawable.ic_local_dining_white_24dp, "Food"),
                        new BottomBarFragment(VideoFragment.newInstance(R.layout.video_layout), R.drawable.ic_favorite_white_24dp, "Favorites")
            
                );
            

            设置徽章数量:

              BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(1, "#E91E63", 4);
              unreadMessages.show();
              unreadMessages.setCount(4);
              unreadMessages.setAnimationDuration(200);
              unreadMessages.setAutoShowAfterUnSelection(true);
            

            LibraryFragment.java:

            import android.os.Bundle;
            import android.support.annotation.Nullable;
            import android.support.v4.app.Fragment;
            import android.view.LayoutInflater;
            import android.view.View;
            import android.view.ViewGroup;
            
            public class LibraryFragment extends Fragment {
                private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";
            
                public LibraryFragment() {
                }
            
                public static LibraryFragment newInstance(int resource) {
                    Bundle args = new Bundle();
                    args.putInt(STARTING_TEXT, resource);
            
                    LibraryFragment sampleFragment = new LibraryFragment();
                    sampleFragment.setArguments(args);
            
                    return sampleFragment;
                }
            
                @Nullable
                @Override
                public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            
            
                    View view = LayoutInflater.from(getActivity()).inflate(
                            getArguments().getInt(STARTING_TEXT), null);
                    return view;
            
            
                }
            

            【讨论】:

              【解决方案13】:
              <android.support.design.widget.BottomNavigationView
                  android:id="@+id/navigation"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_gravity="bottom"
                  android:background="?android:attr/windowBackground"
                  app:menu="@menu/navigation" />
              

              navigation.xml(内部菜单)

              <?xml version="1.0" encoding="utf-8"?>
              <menu xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto">
              
                  <item
                      android:id="@+id/navigation_home"
                      android:icon="@drawable/ic_home_black_24dp"
                      android:title="@string/title_home"
                      app:showAsAction="always|withText"
                      android:enabled="true"/>
              

              onCreate()方法内,

              BottomNavigationView navigation = (BottomNavigationView)findViewById(R.id.navigation);
              //Dont forgot this line     
              BottomNavigationViewHelper.disableShiftMode(navigation);
              

              如下创建类。

              public class BottomNavigationViewHelper {
                  public static void disableShiftMode(BottomNavigationView view) {
                      BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
                      try {
                          Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
                          shiftingMode.setAccessible(true);
                          shiftingMode.setBoolean(menuView, false);
                          shiftingMode.setAccessible(false);
                          for (int i = 0; i < menuView.getChildCount(); i++) {
                              BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                              //noinspection RestrictedApi
                              item.setShiftingMode(false);
                              // set once again checked value, so view will be updated
                              //noinspection RestrictedApi
                              item.setChecked(item.getItemData().isChecked());
                          }
                      } catch (NoSuchFieldException e) {
                          Log.e("BNVHelper", "Unable to get shift mode field", e);
                      } catch (IllegalAccessException e) {
                          Log.e("BNVHelper", "Unable to change value of shift mode", e);
                      }
                  }
              }
              

              【讨论】:

                【解决方案14】:

                您可以根据上述答案创建布局 如果有人想在 kotlin 中使用它:-

                 private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
                    when (item.itemId) {
                        R.id.images -> {
                          // do your work....
                            return@OnNavigationItemSelectedListener true
                        }
                       R.id.videos ->
                         {
                          // do your work....
                            return@OnNavigationItemSelectedListener true
                        }
                    }
                    false
                }
                

                然后在 oncreate 中你可以将上面的监听器设置为你的视图

                   mDataBinding?.navigation?.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2020-02-07
                  • 1970-01-01
                  • 2017-07-18
                  • 2023-01-20
                  相关资源
                  最近更新 更多