Как сделать макет с помощью View заполнить оставшееся пространство? - PullRequest
175 голосов
/ 11 июня 2011

Я проектирую пользовательский интерфейс своего приложения.Мне нужен макет выглядит следующим образом:

Example of desired layout

(<и> - кнопки).Проблема в том, что я не знаю, как убедиться, что TextView заполнит оставшееся пространство, с двумя кнопками фиксированного размера.

Если я использую fill_parent для Text View, вторая кнопка (>) может '

Как создать макет, похожий на изображение?

Ответы [ 11 ]

189 голосов
/ 11 сентября 2014

Ответ от woodshy работал для меня, и он проще, чем ответ Унгуряну Ливиу, поскольку он не использует RelativeLayout.Я даю свой макет для ясности:

<LinearLayout 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      >

     <Button
        android:layout_width = "80dp"
        android:layout_weight = "0"
        android:layout_height = "wrap_content"
        android:text="&lt;"/>
     <TextView
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:layout_weight = "1"/>
     <Button
        android:layout_width = "80dp"
        android:layout_weight = "0"
        android:layout_height = "wrap_content"
        android:text="&gt;"/>   
 </LinearLayout>
92 голосов
/ 11 июня 2011

В случае, если помещено в LinearLayout, установите для свойства Layout_weight для <и> значение 0 и> для 0 и 1 для TextView.
В случае RelativeLayout выровняйте <и> по левому и правому краям и установите «Layout для Свойство TextView слева от "и" Расположение справа от "с идентификаторами <и>

71 голосов
/ 11 июня 2011

Если вы используете RelativeLayout, вы можете сделать это примерно так:

<RelativeLayout
    android:layout_width = "fill_parent"
    android:layout_height = "fill_parent">
    <ImageView
        android:id = "@+id/my_image"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_alignParentTop ="true" />
    <RelativeLayout
        android:id="@+id/layout_bottom"
        android:layout_width="fill_parent"
        android:layout_height = "50dp"
        android:layout_alignParentBottom = "true">
        <Button
            android:id = "@+id/but_left"
            android:layout_width = "80dp"
            android:layout_height = "wrap_content"
            android:text="&lt;"
            android:layout_alignParentLeft = "true"/>
        <TextView
            android:layout_width = "fill_parent"
            android:layout_height = "wrap_content"
            android:layout_toLeftOf = "@+id/but_right"
            android:layout_toRightOf = "@id/but_left" />
        <Button
            android:id = "@id/but_right"
            android:layout_width = "80dp"
            android:layout_height = "wrap_content"
            android:text="&gt;"
            android:layout_alignParentRight = "true"/>
    </RelativeLayout>
</RelativeLayout>
28 голосов
/ 02 августа 2017

Используя ConstraintLayout, я нашел что-то вроде

<Button
    android:id="@+id/left_button"
    android:layout_width="80dp"
    android:layout_height="48dp"
    android:text="&lt;"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/left_button"
    app:layout_constraintRight_toLeftOf="@+id/right_button"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/right_button"
    android:layout_width="80dp"
    android:layout_height="48dp"
    android:text="&gt;"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

работает. Ключ устанавливает правильные ограничения для правого, левого, верхнего и нижнего краев, затем устанавливает ширину и высоту на 0dp и позволяет ему определить свой собственный размер.

7 голосов
/ 13 февраля 2014

Это просто Вы устанавливаете minWidth или minHeight, в зависимости от того, что вы ищете, горизонтальный или вертикальный. А для другого объекта (того, которым вы хотите заполнить оставшееся пространство) вы устанавливаете вес 1 (установите ширину, чтобы обернуть его содержимое), поэтому он заполнит остальную часть области.

<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center|left"
        android:orientation="vertical" >
</LinearLayout>
<LinearLayout
        android:layout_width="80dp"
        android:layout_height="fill_parent"
        android:minWidth="80dp" >
</LinearLayout>
4 голосов
/ 04 ноября 2015

вы можете использовать высокий атрибут layout_weight. Ниже вы можете увидеть макет, где ListView занимает все свободное место с кнопками внизу:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".ConfigurationActivity"
    android:orientation="vertical"
    >

        <ListView
            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1000"
            />


        <Button
            android:id="@+id/btnCreateNewRule"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Create New Rule" />



        <Button
            android:id="@+id/btnConfigureOk"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Ok" />


</LinearLayout>
3 голосов
/ 22 апреля 2015

Для тех, у кого такой же глюк с <LinearLayout...>, как у меня:

Важно указать android:layout_width="fill_parent", оно не будет работать с wrap_content.

OTOH, вы можете опустить android:layout_weight = "0", это не обязательно.

Мой код в основном совпадает с кодом в https://stackoverflow.com/a/25781167/755804 (автор Вивек Пандей)

2 голосов
/ 05 ноября 2015

Вам следует избегать вложения 2 относительных макетов, поскольку для относительного макета всегда используется 2 прохода для рисования (против 1 для любого другого типа макета).Это становится экспоненциальным, когда вы их вкладываете.Вы должны использовать линейный макет с шириной = 0 и весом = 1 для элемента, который вы хотите заполнить оставшееся пространство.Этот ответ лучше для производительности и практики.Помните: используйте относительное расположение ТОЛЬКО, когда у вас нет другого выбора.

<?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:orientation="vertical">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/prev_button"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="&lt;" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ellipsize="end"
            android:singleLine="true"
            android:gravity="center"
            android:text="TextView" />

        <Button
            android:id="@+id/next_button"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="&gt;" />
    </LinearLayout>
</LinearLayout>
0 голосов
/ 28 апреля 2019

я нашел

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginEnd="10dp"
        android:fontFamily="casual"
        android:text="(By Zeus B0t)"
     ``   android:textSize="10sp"
        android:gravity="bottom"
        android:textStyle="italic" />
0 голосов
/ 18 мая 2017

используйте Relativelayout для переноса LinearLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:round="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
    <Button
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text="&lt;"/>
    <TextView
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:layout_weight = "1"/>
    <Button
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text="&gt;"/>

</LinearLayout>

</RelativeLayout>`
...