Android笔记:如何解决java中的setPeekHeight()没有给出与xml中相同的结果?
【摘要】
今天在我的应用程序中使用Bottom Sheets。
<include
android:layout_height="wrap_content"
android:l...
今天在我的应用程序中使用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"
/>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
当我将peek高度从这个xml更改为120dp时,我得到了正确的视图。但是当尝试从java做同样的事情时,我会得到不同的结果,即高度小于xml。
bottomSheetBehavior.setPeekHeight(120);
出现这样的问题是当然的,setPeekHeight()(以及许多其他大小/维度相关的方法)为其参数获取像素值。这意味着您需要先将dp值转换为px。执行此操作的最佳方法是定义dimen资源值,然后在代码中获取它:
<dimen name="peek_height">120dp</dimen>
- 1
然后在代码里写
int peekHeightPx = context.getResources().getDimensionPixelSize(R.dimen.peek_height);
bottomSheetBehavior.setPeekHeight(peekHeightPx);
- 1
- 2
或者,也可以使用DisplayMetrics自己进行计算:
int peekHeightPx = (int) (context.getResources().getDisplayMetrics().density * 120);
bottomSheetBehavior.setPeekHeight(peekHeightPx);
- 1
- 2
文章来源: chengsy.blog.csdn.net,作者:程思扬,版权归原作者所有,如需转载,请联系作者。
原文链接:chengsy.blog.csdn.net/article/details/87894627
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)