Android - how to get height of bottomnavigationview

Viewed 18405

I create a bottom navigation view. I try to get height of bottom navigation view. Material design says that the height should be 56dp. I don't want to use hard coded value, because I am not sure that this value won't change. How can I get the dimension of the view programmatically like getting status bar's height.

int resourceId =getResources().getIdentifier("status_bar_height","dimen","android");
if (resourceId > 0) {
     height = getResources().getDimensionPixelSize(resourceId);
} 
3 Answers

This is basic code for achieve the height of 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();

Here is another approach. To get the height of BottomNavigationView programatically, I use ViewTreeObserver. This allows me to get the right value of the view after its drawn. Below is the sample code:

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
                    }
                });
            }

It is very important to remove viewObserver listener once we get the view's height, I am removing viewObserver using:

removeOnGlobalLayoutListener(this)

So that it stops listening to every change in that view.

Related