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的高度
最終的效果如所示: