如何使View的高度与NestedScrollView上方的空间匹配?

时间:2019-11-06 15:48:28

标签: android nestedscrollview

我想要一个MapView像我已经拥有的那样,将一个永久性底部工作表(NestedScrollView)上方的所有空间都占用,您将在下图看到。

Example of a NestedScrollView with BottomSheetBehavior combined with map

对于MapView,我正在使用 android:layout_height =“ 238dp” 。我尝试将其替换为 android:layout_height =“ match_parent” ,但随后MapView的高度被拉伸,占据了整个屏幕。如上图所示,这是代码。

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="beforeDescendants"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".SpotFormActivity"
    tools:showIn="@layout/spot_form_master_layout">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/save_spot_form_basic"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <com.mapbox.mapboxsdk.maps.MapView
                android:id="@+id/mapview2"
                android:layout_width="match_parent"
                **android:layout_height="238dp"** />

        </androidx.coordinatorlayout.widget.CoordinatorLayout>

        <androidx.core.widget.NestedScrollView
            android:id="@+id/spot_form_scrollview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FFF"
            android:paddingBottom="60dp"
     app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
           ....
        </androidx.core.widget.NestedScrollView>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

我不想使用 android:layout_height =“ 238dp ,因为在屏幕较大的设备中,地图高度不会自动调整。有没有人建议采用更好的方法?

1 个答案:

答案 0 :(得分:0)

这是我大多数时候用来更改物品高度的工具,它适合于不同的设备
首先获取设备的高度:

public static int getDaviceHeight(Activity activity){
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        height=displayMetrics.heightPixels;
        return height;

    }

然后更改项目高度:

MapView mapView = (MapView) v.findViewById(R.id.mapView2);
        mapView.getLayoutParams().height=(getDaviceHeight(this))/3;
        //ofcourse you can change the number and devide the total height as much as you want