java 中的 setPeekHeight() 未给出与 xml 中相同的结果

setPeekHeight() in java not giving same result as in xml

我在我的应用程序中使用 Bottom Sheets。

<include
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        layout="@layout/layout_book"

        app:layout_behavior="@string/bottom_sheet_behavior"
        app:behavior_peekHeight="0dp"
        />

这是我的底部 sheet,当我将窥视高度从这个 xml 更改为 120dp 时,我得到了正确的视图。 但是当尝试从 java 做同样的事情时,我得到不同的结果,即高度小于 xml.

bottomSheetBehavior.setPeekHeight(120);

理想情况下不应该是这样的。我对此一无所知。 谢谢

setPeekHeight()(以及许多其他 size/dimension 相关方法)将 pixel 值作为参数。这意味着您需要先将 dp 值转换为 px。最好的方法是定义一个 dimen 资源值,然后在代码中获取它:

<dimen name="peek_height">120dp</dimen>
int peekHeightPx = context.getResources().getDimensionPixelSize(R.dimen.peek_height);
bottomSheetBehavior.setPeekHeight(peekHeightPx);

或者,您可以使用 DisplayMetrics 自己计算:

int peekHeightPx = (int) (context.getResources().getDisplayMetrics().density * 120);
bottomSheetBehavior.setPeekHeight(peekHeightPx);