GridLayout — выравнивание элемента

Я пытаюсь уменьшить расстояние между двумя столбцами, пробовал использовать отрицательные поля, но не сработало. Есть ли способ приблизить 2 элемента изображения?

<?xml version="1.0" encoding="utf-8"?>
<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:useDefaultMargins="true"
    android:alignmentMode="alignBounds"
    android:columnOrderPreserved="false"
    android:layout_gravity="center"
    android:orientation="horizontal"
    android:stretchMode="columnWidth"
    android:background="@color/orange"
    android:textSize="12sp"
    android:columnCount="8">
  <ImageButton
        android:id="@+id/settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnSpan="1"
        android:layout_gravity="left"
        android:src="@drawable/settings" />
    <TextView
        android:id="@+id/currentCityName"
        android:layout_column="2"     
        android:textSize="22sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="City name"
        android:layout_columnSpan="4"
        android:layout_gravity="center_horizontal"

        />
  <ImageButton
        android:id="@+id/refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="7"

        android:layout_columnSpan="1"
        android:layout_gravity="right"
        android:src="@drawable/reload" />
    <ImageView
        android:id="@+id/currentWeatherImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnSpan="8"
        android:layout_rowSpan="3"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/cloud" />
    <ImageView
        android:id="@+id/humidityIcon"
        android:layout_width="20dp"         
        android:paddingTop="10dp"
        android:paddingLeft="0dp"
        android:paddingRight="0dp"
        android:layout_marginRight="0dp"
        android:layout_gravity="left"
        android:background="#000000"
        android:src="@drawable/humidity" />
    <TextView
        android:id="@+id/humidity"       
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="13sp"
        android:paddingTop="10dp"
        android:paddingLeft="0dp"
        android:layout_marginLeft="0dp"
        android:layout_gravity="left"
        android:background="#FFFFFF"
        />
    <TextView
        android:id="@+id/temperature"
        android:layout_columnSpan="4"
        android:layout_rowSpan="2"
        android:textSize="49sp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="5dp"
        android:layout_gravity="center_horizontal"/>
    <ImageView
        android:id="@+id/windSpeedIcon"
        android:layout_width="30dp"
        android:layout_marginRight="1dp"
        android:paddingRight="1dp"
        android:layout_gravity="right"
        android:src="@drawable/wind" />

    <TextView
        android:id="@+id/windSpeed"
        android:textSize="12sp"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        />
    <!-- android:layout_width="40dp" -->
    <TextView
        android:id="@+id/precipitationIcon"
        android:textSize="28sp"
        android:layout_width="40dp"
        />
    <TextView
        android:id="@+id/precipitation"
        android:layout_column="0"
        android:textSize="13sp"
        android:layout_width="40dp"
        />
    <TextView
        android:id="@+id/windDirection16Point"          
        android:textSize="13sp"
        android:layout_width="80dp"
        android:layout_columnSpan="2"
        />
    <TextView
    android:id="@+id/weatherDescription"
    android:layout_gravity="center_horizontal"
    android:layout_row="7"
    android:layout_columnSpan="8"/>

<TextView
    android:id="@+id/section_label"
    android:layout_margin="5dp" 
    android:layout_columnSpan="8" />    
<EditText
    android:minLines="4"
    android:maxLines="4"
    android:id="@+id/edit"
    android:layout_columnSpan="8"/>   

output image


person Gaurav    schedule 23.04.2013    source источник


Ответы (5)


Я предлагаю реализовать все представление с помощью RelativeLayout, это должно быть лучшим решением для всего представления.

person Raanan    schedule 30.04.2013
comment
Это кажется тривиальным в RelativeLayout я бы использовал это. - person draksia; 01.05.2013

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

То, что вы должны были использовать для своего конкретного макета, представляет собой комбинацию относительное позиционирование и составные чертежи (здесь с android:drawableStart).

Результат использования приведенного ниже кода

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="80dp"
    android:background="#d89018"
    android:paddingBottom="4dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="4dp"
    >

    <TextView
        android:id="@+id/temperature"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:text="25 ℃"
        android:textColor="#fff"
        android:textSize="49sp"
        />

    <TextView
        android:id="@+id/humidity"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:drawableStart="@drawable/humidity"
        android:gravity="center_vertical"
        android:text="83 %"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/windSpeed"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:drawableStart="@drawable/wind"
        android:gravity="center_vertical"
        android:text="19 km/h"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/precipitation"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:drawableStart="@drawable/precipitation"
        android:gravity="center_vertical"
        android:text="0.1 mm"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/windDirection16Point"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignLeft="@id/windSpeed"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:drawableStart="@drawable/windDirection"
        android:gravity="center_vertical"
        android:text="NNW"
        android:textColor="#fff"
        />

</RelativeLayout>

Мало того, что этот макет проще, вы также позволяете Android позаботиться обо всех интервалах за вас. Чтобы изменить расстояние между составным рисунком и текстом, используйте android:drawablePadding в приведенном выше коде макета; в коде Java это будет TextView.setCompoundDrawablePadding) .


Иконки, использованные в примере: вода, windsock, дождливая погода и роза ветров.

person Diti    schedule 01.09.2016

Я думаю, что происходит то, что ваши представления растягиваются, потому что они пытаются соответствовать ширине другого представления в своих столбцах.

Попробуйте уменьшить columnSpan ваших представлений или разделить макет на два отдельных GridLayouts.

Или рассмотрите возможность использования другого макета вообще. Я бы порекомендовал здесь RelativeLayout вместо GridLayout, но я не знаю, как это вписывается в большее окно.

person Jschools    schedule 23.04.2013
comment
Когда я размещаю элементы внутри LinearLayout (вложенные в gridlayout), элемент вообще не отображается pastebin.com/4wXpmV9d - person Gaurav; 25.04.2013

попробуй это:

введите здесь описание изображения

<?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="100dp">

    <LinearLayout
      android:id="@+id/col1"
      android:layout_width="match_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical"
      android:layout_weight="2.4"
      >
        <LinearLayout
          android:id="@+id/col1_row1"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_vertical"
          >   
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/icon"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="83%"/>
      </LinearLayout>         
        <LinearLayout
          android:id="@+id/col1_row2"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_vertical"
          >   
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/icon"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="1.0mm"/>
      </LinearLayout>
    </LinearLayout>  

    <LinearLayout
      android:id="@+id/col2"
      android:layout_width="match_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical"
      android:layout_weight="2.0"
      android:gravity="center"
      >
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="25'"
          android:textSize="50dp"
          />      
    </LinearLayout>

    <LinearLayout
      android:id="@+id/col3"
      android:layout_width="match_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical"
      android:layout_weight="2.4"
      >
        <LinearLayout
          android:id="@+id/col3_row1"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_vertical"
          >   
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/icon"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="19Km"/>
      </LinearLayout>         
        <LinearLayout
          android:id="@+id/col3_row2"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_vertical"
          >   
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/icon"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="NNW"/>
      </LinearLayout>
    </LinearLayout>

</LinearLayout>
person Mbt925    schedule 27.04.2013
comment
Глубокие макеты. Макеты со слишком большим количеством вложений плохо влияют на производительность. Рассмотрите возможность использования более плоских макетов, таких как RelativeLayout или GridLayout, для повышения производительности. Максимальная глубина по умолчанию — 10. developer.android.com/training/improving -макеты/ - person Raanan; 02.05.2013
comment
Я не думаю, что глубина 3 слишком много! - person Mbt925; 02.05.2013
comment
Вам предлагается поспорить с примером в статье, на которую я дал ссылку. - person Raanan; 02.05.2013
comment
вы правы, если запрошенный макет был окончательным! Я предполагаю, что он, вероятно, вырастет и будет содержать больше предметов. поэтому простого gridlayout недостаточно. - person Mbt925; 02.05.2013
comment
Если он добавит больше элементов, это будет лучшая причина сделать его более эффективным, и, вероятно, будет проще добавлять элементы с помощью RelativeLayout. - person Raanan; 02.05.2013
comment
если больше предметов можно просто упорядочить! но вложенный дизайн, очевидно, нуждается в многоуровневой компоновке. но в случае текущего вопроса, я даю право вам. - person Mbt925; 03.05.2013

Я думаю, вы должны изменить usedefaultMargins на false и указать свои собственные поля для элементов.

android:useDefaultMargins="false";
person Ravi    schedule 29.04.2013