android底部功能表列實現

來源:互聯網
上載者:User

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的高度

最終的效果如所示:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.