首页 > 解决方案 > 如何在 Android 中以编程方式创建和扩展 BottomNavigationView?

问题描述

首先,我想解释一下“以编程方式”是什么意思,就我而言,它的意思是“根本没有 XML”

我的目标很简单,但我正在努力以编程方式完成所有事情:

  1. 在屏幕底部放置一个 BottomNavigationView

  2. 用 4 个按钮膨胀 BottomNavigationView,每个按钮都有一个图标但没有标题

  3. 在选择的侦听器上设置并选择时,找出选择的项目

这是我为 1 和 2 而不是 3 的代码:

public class BottomBarLayout extends RelativeLayout {
    BottomNavigationView bottomBar;

    public BottomBarLayout(Context context) {
        super(context);

        configureBottomBar();
    }

    private void configureBottomBar() {
        bottomBar = new BottomNavigationView(this.getContext());

        // Inflate bottom bar with 4 items without titles but with icons
        bottomBar.getMenu().add(null).setIcon(R.drawable.ic_...);
        bottomBar.getMenu().add(null).setIcon(R.drawable.ic_...);
        bottomBar.getMenu().add(null).setIcon(R.drawable.ic_...);
        bottomBar.getMenu().add(null).setIcon(R.drawable.ic_...);
        bottomBar.setOnNavigationItemSelectedListener(menuItem -> onSelectNavigationItem(menuItem));

        // Add layout rules to stick bottomBar to bottom of screen
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        addView(bottomBar, params);
    }
}

private boolean onSelectNavigationItem(MenuItem item) {
    // -------------------->Question here<------------------------
    return true;
}

我的问题是,在onSelectNavigationItem听众中,我怎么知道选择了哪个项目?我没有为这 4 个项目中的任何一个分配一个 ID。如果我可以分配ID,如何分配?如果没有,我怎么知道选择了哪个项目?谢谢你。

标签: android

解决方案


推荐阅读