天天看點

擷取 Android Toolbar的真實準确高度問題

項目中設定了Toolbar代碼片段如下

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:gravity="center_vertical">
           

Toolbar裡包含一個子view設定高度45dp

然後項目中需要在界面顯示前擷取Toolbar 的高度,動态設定其他view

但是代碼擷取的高度總是比實際高度小16px,Toolbar的高度也不是xml裡設定的45dp,實際是56dp,檢查了所有的代碼沒有找到設定的地方,于是用layout inspector 檢視下了機器的實際界面:

擷取 Android Toolbar的真實準确高度問題

發現Toolbar裡還包含了一個ActionMenuView的子View,是Toolbar 用來顯示Menu的裡面的 Item 最小高度為56dp,源碼如下:

/**
 * ActionMenuView is a presentation of a series of menu options as a View. It provides
 * several top level options as action buttons while spilling remaining options over as
 * items in an overflow menu. This allows applications to present packs of actions inline with
 * specific or repeating content.
 */
public class ActionMenuView extends LinearLayoutCompat implements MenuBuilder.ItemInvoker,
        MenuView {

    private static final String TAG = "ActionMenuView";

    static final int MIN_CELL_SIZE = 56; // dips
           

加上最小56dp後問題解決