Search code examples
androidandroid-scrollview

First child of LinearLayout inside ScrollView with 1/3 space of device height


I have a ScrollView with a LinearLayout with 3 elements inside. I would like that the first element has a height of 1/3 the height of the device height and the other 2 with wrap_content, is this possible to do in xml or how would you do this? Using weight alone it does not seem possible because the LinearLayout inside the ScrollView could be longer than the device's height.


Solution

  • According to Android docs, android:layout_weight:

    Indicates how much of the extra space in the LinearLayout is allocated to the view associated with these LayoutParams. Specify 0 if the view should not be stretched. Otherwise the extra pixels will be pro-rated among all views whose weight is greater than 0.

    This implies that the weight is not dependent on the screen height, but rather only on its parent view, so you can't achieve that from xml. To achieve this I would compute the height of the screen and then resize the view:

    Display screen = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    screen.getSize(size);
    int screenHeight = size.y;
    
    myView.setLayoutParams(new LayoutParams(myView.getWidth(), screenHeight / 3));