Translucent StatusBar with dynamic ActionBar color in Android

后端 未结 1 1135
不思量自难忘°
不思量自难忘° 2021-01-12 08:24

I\'m trying to realize a translucent statusbar (so that my navigation-view is BEHIND the statusbar) but still like to change the color of my actionbar dynam

1条回答
  •  一生所求
    2021-01-12 09:10

    Actually, it's fairly easy to implement.

    First step - is to change height of the Toolbar:

    • change height to wrap_content

    so for me it looks like this:

        
    

    Then you override resources for v19:

        
        
                
        
    

    Then, in the Activity, setting padding for the Toolbar:

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
        ......
        ......
        public int getStatusBarHeight() {
            int result = 0;
    
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
                if (resourceId > 0) {
                    result = getResources().getDimensionPixelSize(resourceId);
                }
            }
            return result;
        }
    

    And actually, it's pretty much it. Now once I want to change colour of the Toolbar, I'm calling this:

        if (getSupportActionBar() != null) {
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.GREEN));
        }
    

    The activity's layout:

    
    
    
        
    
    
        
    
    
    

    NB! On pre-Kitkat OS-versions, status bar remained the same, non-translucent.

    I've uploaded the source code of the test-application to my dropbox - feel free to check it out.

    I hope, it helps

    0 讨论(0)
提交回复
热议问题