Android开发中有的时候需要把菜单显示在屏幕的底部,但是Android本身没有提供这样的控件,因此需要自己写代码来实现,网上Google一下有关这个主题的网页,最终都是从这篇《android实现底部菜单栏》文复制过去的(源代码在这里),但是如果你把这篇文里的代码全部复制过去,你会发现在模拟器里看不到底部的菜单栏,问题出在哪儿呢?仔细检查一下/res/layout/main.xml这个文件里的下面这节:

<LinearLayout xmlns:andro>
</LinearLayout>

问题就出在上面标红的那行,这里把屏幕中间内容区的高度写死了,如果你的手机屏幕高度没那么高,很显然菜单栏会被挤出屏幕最底端。

解决这个问题其实很简单,首先调用WindowManager的getDefaultDisplay()方法获取屏幕的高度,然后减去Activity Titlebar的高度和将要显示的菜单栏高度,剩下的差值就应该是内容区的高度了。具体的代码示例如下:

修改上面的布局如下:

<LinearLayout xmlns:andro/>
    </LinearLayout>

其中里面LinearLayout的layout_height值随便写个有效值。

再在Activity的onCreate方法里写上设置这个LinearLayout高度的代码,如下所示:

WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
int screenHeight = display.getHeight(); //屏幕高度

int titlebarHeight;  //Activity的标题栏高度

int menuBarHeight; // 底部菜单栏的高度

int topContentHeight; //最上端内容区高度(假如在这个contentBody上端还有其他内容的话)

LinearLayout bodyLayout = (LinearLayout) findViewById(R.id.contentBody);
LinearLayout.LayoutParams layParams = (android.widget.LinearLayout.LayoutParams) bodyLayout.getLayoutParams();
layParams.height = screenHeight - titlebarHeight - menuBarHeight - topContentHeight;      
bodyLayout.setLayoutParams(layParams); //设置contentBody的高度

最终的效果如下图所示:

android底部菜单栏实现

相关文章:

  • 2022-12-23
  • 2021-07-08
  • 2021-08-29
  • 2022-12-23
  • 2021-04-16
  • 2021-05-16
  • 2021-09-14
猜你喜欢
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
  • 2022-01-04
  • 2021-11-11
  • 2021-05-24
  • 2022-12-23
相关资源
相似解决方案