Search code examples
androidandroid-layoutfinalrunnable

Accessing private variable outside the method in which it is assigned


I've used Runnable to find height of the Status bar and it's giving correct output.

But how do I access StatusBarHeight outside the run() method of Runnable?

Here is my piece of code:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final RelativeLayout main = (RelativeLayout) findViewById(R.id.main);

        final Rect rectgle = new Rect();
        final Window window = getWindow();

        main.post(new Runnable() {
            @Override
            public void run() {

                window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
                int StatusBarHeight = rectgle.top;
                int contentViewTop = window.findViewById(
                        Window.ID_ANDROID_CONTENT).getTop();
                int TitleBarHeight = contentViewTop - StatusBarHeight;

                Log.i("ScreenDemo", "StatusBar Height= " + StatusBarHeight
                        + " , TitleBar Height = " + TitleBarHeight);
            }
        });
}

P.S. : If I write the code within run() directly in onCreate(), it returns me 0 as UI has not rendered yet.
Any help appreciated.


Solution

  • Your variable StatusBarHeight 's scope is local to the block within, if you want to access it from onCreate() method, then you need to declare it as following way,

    private static int StatusBarHeight;  // class level declaration
    
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final RelativeLayout main = (RelativeLayout) findViewById(R.id.main);
    
            final Rect rectgle = new Rect();
            final Window window = getWindow();
    
            main.post(new Runnable() {
                @Override
                public void run() {
    
                    window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
                    StatusBarHeight = rectgle.top;
                    int contentViewTop = window.findViewById(
                            Window.ID_ANDROID_CONTENT).getTop();
                    int TitleBarHeight = contentViewTop - StatusBarHeight;
    
                    Log.i("ScreenDemo", "StatusBar Height= " + StatusBarHeight
                            + " , TitleBar Height = " + TitleBarHeight);
                }
            });
    }