Макет Android wrap_content с layout_weight = 0 не отображается

Я пытаюсь создать макет со встроенным фрагментом карты Google и некоторой информацией о выбранных маркерах под картой. Я хочу, чтобы информация под картой занимала только то пространство, которое ей нужно, а остальное пространство отдавалось карте.

Насколько я понимаю, layout_weight выделяет дополнительное пространство для различных виджетов пропорционально заданному значению. Итак, если у меня есть виджет с layout_weight = 1 и другой виджет с layout_weight = 0, первый виджет займет все лишнее место, а второй займет только то, что ему нужно. Так что если я даю второй виджет layout_height = wrap_content, то я должен получить то, что хочу. Однако на практике это, похоже, не так. Я изменил много значений, и либо один из виджетов занимает все место, либо ни один из них не занимает. Единственный способ, которым я смог заставить их нормально отображаться, — это установить layout_height второго виджета на определенное значение.

Это может быть частью проблемы, но я динамически заполняю виджеты map_frag_event_icon, map_frag_person и map_frag_event_details.


макет.xml

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width = "match_parent"
    android:layout_height = "0dp"
    android:layout_margin = "@dimen/fragment_margins"
    android:orientation = "vertical">

    <fragment
        xmlns:tools = "http://schemas.android.com/tools"
        xmlns:map = "http://schemas.android.com/apk/res-auto"
        android:id = "@+id/map_frag_google_map"
        android:name = "com.google.android.gms.maps.SupportMapFragment"
        android:layout_width = "match_parent"
        android:layout_height = "0dp"
        android:layout_weight = "1"
        android:paddingBottom = "@dimen/fragment_margins"
        tools:context = ".fragment.MapFragment"/>

    <LinearLayout
        android:id = "@+id/map_frag_event_layout"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_weight = "0"
        android:orientation = "horizontal"
        android:gravity = "center_vertical">

        <ImageView
            android:id = "@+id/map_frag_event_icon"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:padding = "@dimen/icon_padding"
            android:layout_weight = "0" />

        <LinearLayout
            android:layout_width = "0dp"
            android:layout_height = "match_parent"
            android:layout_weight = "1"
            android:orientation = "vertical"
            android:gravity = "center_vertical">

            <TextView
                android:id = "@+id/map_frag_event_person"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:textSize = "@dimen/text_size"/>

            <TextView
                android:id = "@+id/map_frag_event_details"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:textSize = "@dimen/text_size"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

строки.xml

<resources>
    <string name = "app_name">Family Map</string>
    <string name = "title_activity_maps">Map</string>

    <dimen name = "fragment_margins">8dp</dimen>
    <dimen name = "horizontal_layout_padding">8dp</dimen>
    <dimen name = "vertical_layout_padding">4dp</dimen>
    <dimen name = "icon_size">48sp</dimen>
    <dimen name = "icon_padding">8dp</dimen>
    <dimen name = "text_size">20sp</dimen>
    <dimen name = "small_text_size">14sp</dimen>
    <dimen name = "large_text_size">24sp</dimen>

    <dimen name = "map_event_layout_height">120sp</dimen>
    <dimen name = "map_event_icon_size">40sp</dimen>

</resources>

РЕДАКТИРОВАТЬ

Вот общий дизайн, который я ищу, но я хочу, чтобы белое пространство с текстом было как можно меньше, и я хочу создать настройку для изменения размера текста, поэтому нижнее белое пространство должно быть динамическим.

Макет Android wrap_content с layout_weight = 0 не отображается

Пожалуйста, дайте объяснение того, что происходит вместе с решением, если вы можете.

удалить android:layout_weight = "0"

Muhammad Muzammil Sharif 02.04.2019 08:50

Почему родитель android:layout_height = "0dp" ?

Faysal Ahmed 02.04.2019 08:51

@Mahammad Я пробовал это, и это не сработало.

Jacob Bischoff 02.04.2019 08:55

попробуйте решение @FaysalAhmed

Muhammad Muzammil Sharif 02.04.2019 08:58

не могли бы вы поделиться дизайном здесь?

hasan_shaikh 02.04.2019 08:59

@hasan_shaikh Я отредактировал вопрос, включив в него пример дизайна с текущими проблемами.

Jacob Bischoff 02.04.2019 09:31
0
6
449
5
Перейти к ответу Данный вопрос помечен как решенный

Ответы 5

Во фрагменте оставьте android:layout_weight = "1", а в LinearLayout примените, например, android:layout_weight = "0.5". Проверьте результат, а затем измените значения в соответствии с вашими потребностями. Посмотрите на это как на относительные проценты, поэтому 1 к 0,5 будет от 66% до 33%.

Попробуйте с макетом ниже:

    <fragment xmlns:map = "http://schemas.android.com/apk/res-auto"
        xmlns:tools = "http://schemas.android.com/tools"
        android:id = "@+id/map_frag_google_map"
        android:name = "com.google.android.gms.maps.SupportMapFragment"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:layout_above = "@+id/map_frag_event_layout"
        android:paddingBottom = "@dimen/fragment_margins"
        tools:context = ".fragment.MapFragment" />

    <LinearLayout
        android:id = "@+id/map_frag_event_layout"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_alignParentBottom = "true"
        android:gravity = "center_vertical"
        android:orientation = "horizontal">

        <ImageView
            android:id = "@+id/map_frag_event_icon"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:layout_weight = "0"
            android:padding = "@dimen/icon_padding" />

        <LinearLayout
            android:layout_width = "0dp"
            android:layout_height = "match_parent"
            android:layout_weight = "1"
            android:gravity = "center_vertical"
            android:orientation = "vertical">

            <TextView
                android:id = "@+id/map_frag_event_person"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:textSize = "@dimen/text_size" />

            <TextView
                android:id = "@+id/map_frag_event_details"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:textSize = "@dimen/text_size" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

Попробуйте код ниже:

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:layout_margin = "@dimen/fragment_margins"
    android:orientation = "vertical">

    <fragment
        xmlns:tools = "http://schemas.android.com/tools"
        xmlns:map = "http://schemas.android.com/apk/res-auto"
        android:id = "@+id/map_frag_google_map"
        android:name = "com.google.android.gms.maps.SupportMapFragment"
        android:id = "@+id/map_frag_google_map"
        android:layout_width = "match_parent"
        android:layout_height = "0dp"
        android:layout_weight = "1"
        android:paddingBottom = "@dimen/fragment_margins"
        tools:context = ".fragment.MapFragment" />

    <LinearLayout
        android:id = "@+id/map_frag_event_layout"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:gravity = "center_vertical"
        android:orientation = "horizontal">

        <ImageView
            android:id = "@+id/map_frag_event_icon"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:padding = "@dimen/icon_padding"
            android:src = "@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width = "0dp"
            android:layout_height = "match_parent"
            android:layout_weight = "1"
            android:gravity = "center_vertical"
            android:orientation = "vertical">

            <TextView
                android:id = "@+id/map_frag_event_person"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:textSize = "@dimen/text_size" />

            <TextView
                android:id = "@+id/map_frag_event_details"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:textSize = "@dimen/text_size" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Замените свой xml-код этим,

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "0dp"
android:layout_margin = "@dimen/fragment_margins"
android:orientation = "vertical">

<fragment
    xmlns:tools = "http://schemas.android.com/tools"
    xmlns:map = "http://schemas.android.com/apk/res-auto"
    android:id = "@+id/map_frag_google_map"
    android:name = "com.google.android.gms.maps.SupportMapFragment"
    android:layout_width = "match_parent"
    android:layout_height = "0dp"
    android:layout_weight = "0.8"
    android:paddingBottom = "@dimen/fragment_margins"
    tools:context = ".fragment.MapFragment"/>

<LinearLayout
    android:id = "@+id/map_frag_event_layout"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:layout_weight = "0.2"
    android:orientation = "horizontal"
    android:gravity = "center_vertical">

    <ImageView
        android:id = "@+id/map_frag_event_icon"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:padding = "@dimen/icon_padding"
        android:layout_weight = "0" />

    <LinearLayout
        android:layout_width = "0dp"
        android:layout_height = "match_parent"
        android:layout_weight = "1"
        android:orientation = "vertical"
        android:gravity = "center_vertical">

        <TextView
            android:id = "@+id/map_frag_event_person"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"
            android:textSize = "@dimen/text_size"/>

        <TextView
            android:id = "@+id/map_frag_event_details"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"
            android:textSize = "@dimen/text_size"/>

    </LinearLayout>

</LinearLayout>

Вы устанавливаете вес равным 1 для обоих представлений. Так

Ответ принят как подходящий

Я обнаружил две проблемы с моим исходным кодом, который я опубликовал. Я не знаю, когда я добавил это во время моего первоначального тестирования, но были две фатальные ошибки. В корне LinearLayout у меня было layout_height = "0dp" и должно было быть layout_height = "match_parent". А в LinearLayout, содержащем два TextViews, у меня было layout_height = "match_parent", а должно было быть layout_height = "wrap_content".

После исправления этих двух ошибок оригинальный комментарий @MuhammadMuzammilSharif об удалении layout_weight = "0" сработал.


макет.xml

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:layout_margin = "@dimen/fragment_margins"
    android:orientation = "vertical">

    <fragment
        xmlns:tools = "http://schemas.android.com/tools"
        xmlns:map = "http://schemas.android.com/apk/res-auto"
        android:id = "@+id/map_frag_google_map"
        android:name = "com.google.android.gms.maps.SupportMapFragment"
        android:layout_width = "match_parent"
        android:layout_height = "0dp"
        android:layout_weight = "1"
        android:paddingBottom = "@dimen/fragment_margins"
        tools:context = ".fragment.MapFragment"/>

    <LinearLayout
        android:id = "@+id/map_frag_event_layout"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:orientation = "horizontal"
        android:gravity = "center_vertical">

        <ImageView
            android:id = "@+id/map_frag_event_icon"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:padding = "@dimen/icon_padding"/>

        <LinearLayout
            android:layout_width = "0dp"
            android:layout_height = "wrap_content"
            android:layout_weight = "1"
            android:orientation = "vertical"
            android:gravity = "center_vertical">

            <TextView
                android:id = "@+id/map_frag_event_person"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:textSize = "@dimen/text_size"/>

            <TextView
                android:id = "@+id/map_frag_event_details"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:textSize = "@dimen/text_size"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

Другие вопросы по теме