i创建底部导航视图。我尝试获取底部导航视图的高度。材料设计说高度应为56DP。我不想使用硬编码值,因为我不确定此值不会改变。如何以编程方式获得视图的尺寸,例如获得状态栏的高度。
int resourceId =getResources().getIdentifier("status_bar_height","dimen","android");
if (resourceId > 0) {
height = getResources().getDimensionPixelSize(resourceId);
}
您可以在on Create方法中这样做:
bottomNavigationView.post(new Runnable() {
@Override
public void run() {
int height = (int) bottomNavigationView.getMeasuredHeight();
}
});
这将为您提供像素的高度。希望这有帮助
这是实现 bottom> bottomnavigationView 的基本代码,
int resourceId = getResources().getIdentifier("design_bottom_navigation_height", "dimen", this.getPackageName());
int height = 0;
if (resourceId > 0) {
height = getResources().getDimensionPixelSize(resourceId);
}
//height in pixels
Toast.makeText(this, height + "", Toast.LENGTH_SHORT).show();
// if you want the height in dp
float density = getResources().getDisplayMetrics().density;
float dp = height / density;
Toast.makeText(this, dp + "", Toast.LENGTH_SHORT).show();
这是另一种方法。为了从编程中获取底部努力的高度,我使用ViewTreeObserver。这使我能够在绘制之后获得正确的视图值。以下是示例代码:
BottomNavigationView mBottomNavigation= findViewById(R.id.navigation);
ViewTreeObserver viewTreeObserver = mBottomNavigation.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int viewHeight = mBottomNavigation.getHeight();
if (viewHeight != 0)
mBottomNavigation.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//viewWidth = mBottomNavigation.getWidth(); //to get view's width
}
});
}
删除ViewObserver侦听器一旦获得视图的高度,我将使用以下方式删除ViewObserver:
removeOnGlobalLayoutListener(this)
使其不再听取该视图中的每一个更改。