android - 如何在 Android 中以编程方式创建和扩展 BottomNavigationView?
问题描述
首先,我想解释一下“以编程方式”是什么意思,就我而言,它的意思是“根本没有 XML”。
我的目标很简单,但我正在努力以编程方式完成所有事情:
在屏幕底部放置一个 BottomNavigationView
用 4 个按钮膨胀 BottomNavigationView,每个按钮都有一个图标但没有标题
在选择的侦听器上设置并选择时,找出选择的项目
这是我为 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,如何分配?如果没有,我怎么知道选择了哪个项目?谢谢你。
解决方案
推荐阅读
- javascript - 数据表中每行的索引数据数
- python - 在 docker 容器中运行烧瓶应用程序时无法访问端点
- excel - 我们如何在 Excel 中聚合时间序列?
- android - 小型android应用程序生成累积大文件
- ruby-on-rails - 禁用命令提示符后,如何在 Windows 10 Pro 计算机上使用 Ruby on Rails 4 构建应用程序?
- r - 变异功能改变了吗?
- angular - 角度7如何将http服务注入另一个服务
- r - 重新采样R中联立方程的参数值时如何存储循环的输出?
- css - 离子卡等高
- django - 在 url.py 中将域重定向到 django 中的 .com