Рекомендации по получению весов макета для идеального выравнивания кнопок изображений во время работы Android?

#android #xml #layout #imageview #scale

#Android #xml #макет #просмотр изображений #масштабирование

Вопрос:

Мне трудно правильно выровнять кнопки с изображениями во время работы с Android. Как вы можете видеть, все изображения сдвинуты и не выровнены должным образом. И это было после долгого времени настроек.

Мой основной XML-макет:

 <?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="wrap_content" 
     android:adjustViewBounds="true"
    android:layout_weight="1"
        android:gravity="left" 
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"   
    android:layout_width="fill_parent" android:baselineAligned="true">
 <LinearLayout 
    android:orientation="horizontal"
    android:layout_height="158px" 
      android:adjustViewBounds="false"
    android:layout_weight="1"
        android:gravity="left" 
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"  
    android:layout_width="fill_parent" android:baselineAligned="true">  

    <ImageButton         
    android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"

        android:gravity="left" 
   android:adjustViewBounds="false"
  android:scaleType="fitStart"

        android:layout_gravity="left"
        android:background="@drawable/topfula_r1_c1" 
        android:layout_width="wrap_content"
       android:layout_height="wrap_content" 
       android:id="@ id/fluprepare"
       android:layout_weight="1"
       >

       </ImageButton>
    <ImageButton android:scaleType="fitCenter"        
    android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
   android:adjustViewBounds="false"
    android:layout_weight="1"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"
        android:gravity="left" 
        android:layout_gravity="left" android:background="@drawable/topfula_r1_c2" 
        android:layout_width="wrap_content" android:layout_height="wrap_content" 
        android:id="@ id/refreshflu" ></ImageButton>
    <ImageButton android:scaleType="fitEnd"        
    android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
         android:adjustViewBounds="false"
          android:layout_weight="1"
        android:layout_marginBottom="0dp"
        android:gravity="left" 
        android:layout_gravity="left" 
        android:background="@drawable/topfula_r1_c3" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@ id/quitprogram" ></ImageButton>

</LinearLayout>   
 <LinearLayout 
    android:orientation="horizontal"
    android:layout_height="159px" 
      android:adjustViewBounds="true"
    android:layout_weight="1"
        android:gravity="left" 
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"  
    android:layout_width="fill_parent" android:baselineAligned="true">  

    <ImageButton         
    android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"

        android:gravity="left" 
   android:adjustViewBounds="false"
  android:scaleType="fitStart"

        android:layout_gravity="left"
        android:background="@drawable/mid_r1_c1" 
        android:layout_width="wrap_content"
       android:layout_height="wrap_content" 
       android:id="@ id/prepareflu"
       android:layout_weight="1"
       >

       </ImageButton>
    <ImageButton android:scaleType="fitCenter"        
    android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
   android:adjustViewBounds="false"
    android:layout_weight="1"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"
        android:gravity="left" 
        android:layout_gravity="left" android:background="@drawable/mid_r1_c2" 
        android:layout_width="wrap_content" android:layout_height="wrap_content" 
        android:id="@ id/maincdc" ></ImageButton>
    <ImageButton android:scaleType="fitEnd"        
    android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
         android:adjustViewBounds="false"
          android:layout_weight="1"
        android:layout_marginBottom="0dp"
        android:gravity="left" 
        android:layout_gravity="left" 
        android:background="@drawable/mid_r1_c3" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@ id/configsettings" ></ImageButton>

</LinearLayout>   


<LinearLayout 
    android:layout_height="460px" 


   android:adjustViewBounds="false"
    android:layout_weight="1"
        android:gravity="left" 
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"
    android:layout_width="fill_parent" android:orientation="horizontal" android:baselineAligned="true">

<ImageButton android:id="@ id/informationcards" 
android:background="@drawable/bottommain" 
android:layout_gravity="center" android:layout_width="wrap_content" 
android:layout_height="wrap_content" android:layout_weight="1"></ImageButton>
</LinearLayout>
</LinearLayout>
  

Снимок экрана устройства, на котором макет не выравнивается

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

Если требуется дополнительная информация, пожалуйста, дайте мне знать.

[править]

android: baselineAligned = «true» android: layout_weight =»1″ android: baselineAligned =»true»

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

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

Оригинал не склеен

Склеено, и ImageButton сработал awww

Ого-го-го! Я решил это с помощью множества проб и ошибок! в 100 раз меньше кода. нравится wow.

Комментарии:

1. Похоже, что это просто не все подходит. Откуда вы хотите взять дополнительное пространство?

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

3. Вы можете посмотреть видео с исправленным макетом на skyboardsoftware.com 🙂

4. Это хорошее слово, «исправлено» ! 🙂

5. Это было очень близко к удалению как СПАМ из-за поощрения голосования в вашем вопросе (и комментариях), пожалуйста, не делайте этого снова. Кроме того, было бы полезно, если бы вы предоставили решение в качестве ответа и приняли его, что исключило бы это из нашего списка вопросов без ответов.

Ответ №1:

фрагмент из моего main.xml файл, который я использовал в приведенном выше вопросе…

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

    android:background="@drawable/mainlayoutbg2"
  

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

 <TableLayout
android:id="@ id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/mainlayoutbg2"
xmlns:android="http://schemas.android.com/apk/res/android"
android:clickable="true">
<TableRow
    android:id="@ id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:height="100px">
    <Button
        android:clickable="true"
        android:height="100px"
        android:layout_width="wrap_content"
        android:id="@ id/Button02"
        android:layout_height="wrap_content"
        android:background="@null"
        android:text="     "
        android:width="100px"></Button>

    <Button
        android:clickable="true"
        android:height="100px"
        android:layout_width="wrap_content"
        android:id="@ id/refreshflud"
        android:onClick="refreshflu()"
        android:layout_height="wrap_content"
        android:background="@null"
        android:text="     "
        android:width="100px"></Button>

    <Button
        android:clickable="true"
        android:height="100px"
        android:layout_width="wrap_content"
        android:id="@ id/refreshflub"
        android:layout_height="wrap_content"
        android:background="@null"
        android:text="     "
        android:width="100px"></Button>
    <Button
        android:clickable="true"
        android:height="100px"
        android:layout_width="wrap_content"
        android:id="@ id/refreshfluc"
        android:layout_height="wrap_content"
        android:background="@null"
        android:text="     "
        android:width="100px"></Button>
    <Button
        android:height="100px"
        android:text="     "
        android:background="@null"
        android:width="100px"
        android:id="@ id/quitprogram"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></Button>

</TableRow>
  

Я надеюсь, что это сэкономит несколько часов от сеансов разработки у кого-то еще.

Комментарии:

1. Устанавливая высоту всех кнопок на 100 пикселей, вы не считаете, что это будет выглядеть по-разному на каждом устройстве? Попробуйте 100dip для лучшей совместимости между устройствами

2. о, да! отличная идея! спасибо за форматирование исходного кода. Я как раз к этому и подбирался. 🙂 Я думал, что уже переключил px на dip. хороший улов.