Android: How to Programmatically set the size of a Layout

前端 未结 4 559
南方客
南方客 2020-11-28 01:09

As part of an Android App I am building a button set. The buttons are part of a nested set of LinearLayouts. Using weight I have the set resizing itself automatically based

4条回答
  •  情话喂你
    2020-11-28 01:41

    You can get the actual height of called layout with this code:

    public int getLayoutSize() {
    // Get the layout id
        final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
        final AtomicInteger layoutHeight = new AtomicInteger();
    
        root.post(new Runnable() { 
        public void run() { 
            Rect rect = new Rect(); 
            Window win = getWindow();  // Get the Window
                    win.getDecorView().getWindowVisibleDisplayFrame(rect);
    
                    // Get the height of Status Bar
                    int statusBarHeight = rect.top;
    
                    // Get the height occupied by the decoration contents 
                    int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
    
                    // Calculate titleBarHeight by deducting statusBarHeight from contentViewTop  
                    int titleBarHeight = contentViewTop - statusBarHeight; 
                    Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop); 
    
                    // By now we got the height of titleBar & statusBar
                    // Now lets get the screen size
                    DisplayMetrics metrics = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(metrics);   
                    int screenHeight = metrics.heightPixels;
                    int screenWidth = metrics.widthPixels;
                    Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);   
    
                    // Now calculate the height that our layout can be set
                    // If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also 
                    layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
                    Log.i("MY", "Layout Height = " + layoutHeight);   
    
                // Lastly, set the height of the layout       
                FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
                rootParams.height = layoutHeight.get();
                root.setLayoutParams(rootParams);
            }
        });
    
    return layoutHeight.get();
    }
    

提交回复
热议问题