`
gmxstar
  • 浏览: 17562 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

android底部菜单栏实现

阅读更多

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="450px">
</LinearLayout>

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

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

修改上面的布局如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="10px"
        android:id="@+id/contentBody">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center" android:textSize="20px"
            android:layout_gravity="center" android:text="内容区"/>
    </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的高度

最终的效果如下图所示:

 

  • 大小: 14.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics