Равномерно расположенные кнопки фиксированного размера Android

#java #android #xml #button

#java #Android #xml #кнопка

Вопрос:

У меня есть этот XML-документ. Я хочу, чтобы эти изображения кнопок размером 93 на 93 пикселя располагались на равном расстоянии друг от друга. На данный момент настройка веса заставляет их растягиваться и обнимать друг друга, поэтому пробелов нет. Но если я установлю значение weight равным 0, они будут делать то же самое, обнимая друг друга, но заполнят примерно половину экрана.

Кстати, это для альбомной ориентации.

     <LinearLayout android:id="@ id/LinearLayout" android:layout_height="wrap_content"
  android:layout_width="fill_parent">
   <Button 
    android:background="@drawable/a" 
    android:layout_height="93px" 
    android:id="@ id/a"
    android:layout_width="93px" 
    android:layout_weight="1" 
    android:layout_marginLeft="20dip" 
    android:layout_marginTop="30dip"/>
  <Button 
    android:background="@drawable/b" 
    android:layout_height="93px" 
    android:id="@ id/b"
    android:layout_width="93px" 
    android:layout_weight="1"  
    android:layout_marginTop="30dip"/>

  <Button 
    android:background="@drawable/c" 
    android:layout_height="93px" 
    android:id="@ id/c" 
    android:layout_weight="1" 
    android:layout_width="93px"  
    android:layout_marginTop="30dip"/>
  <Button 
    android:background="@drawable/d" 
    android:layout_height="93px" 
    android:id="@ id/d"
    android:layout_width="93px" 
    android:layout_weight="1" 
    android:layout_marginRight="20dip" 
    android:layout_marginTop="30dip" />
    </LinearLayout>
  

a

Ответ №1:

Решение простое.

Вы должны поместить каждую кнопку в отдельный линейный макет и сохранить вес = 1 для каждого линейного макета. Теперь кнопки будут расположены на одинаковом расстоянии друг от друга, независимо от разрешения или ориентации.

ПРИМЕР:-

       <LinearLayout android:id="@ id/LinearLayout" android:layout_height="wrap_content"
      android:layout_width="fill_parent">
      <LinearLayout android:id=@ id/Button1Parent" android:layout_height="wrap_content" android_width="wrap_content" android:weight="1" gravity="center">  
       <Button 
        android:background="@drawable/a" 
        android:layout_height="93px" 
        android:id="@ id/takequiz"
        android:layout_width="93px" 
        android:layout_weight="1" 
        android:layout_marginLeft="20dip" 
        android:layout_marginTop="30dip"/>
</LinearLayout>
<LinearLayout android:id=@ id/Button2Parent" android:layout_height="wrap_content" android_width="wrap_content" android:weight="1" gravity="center">
      <Button 
        android:background="@drawable/b" 
        android:layout_height="93px" 
        android:id="@ id/random"
        android:layout_width="93px" 
        android:layout_weight="1"  
        android:layout_marginTop="30dip"/>
</LinearLayout>
<LinearLayout android:id=@ id/Button3Parent" android:layout_height="wrap_content" android_width="wrap_content" android:weight="1" gravity="center">

      <Button 
        android:background="@drawable/c" 
        android:layout_height="93px" 
        android:id="@ id/search" 
        android:layout_weight="1" 
        android:layout_width="93px"  
        android:layout_marginTop="30dip"/>
</LinearLayout>
<LinearLayout android:id=@ id/Button4Parent" android:layout_height="wrap_content" android_width="wrap_content" android:weight="1" gravity="center">

      <Button 
        android:background="@drawable/d" 
        android:layout_height="93px" 
        android:id="@ id/browse"
        android:layout_width="93px" 
        android:layout_weight="1" 
        android:layout_marginRight="20dip" 
        android:layout_marginTop="30dip" />
        </LinearLayout>
</LinearLayout>
  

Ответ №2:

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

 <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="#000000"
        android:id="@ id/linearLayout01"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:orientation="horizontal"
    >
        <Button
            android:layout_width="0dp"
            android:id="@ id/btn1"
            android:layout_height="93px"
            android:layout_weight="1"
            android:layout_marginRight="5dp"
        ></Button>
        <Button
            android:layout_width="0dp"
            android:id="@ id/btn2"
            android:layout_height="93px"
            android:layout_weight="1"
            android:layout_marginRight="5dp"
        ></Button>
        <Button
            android:layout_width="0dp"
            android:id="@ id/btn3"
            android:layout_height="93px"
            android:layout_weight="1"
            android:layout_marginRight="5dp"
        ></Button>
        <Button
            android:layout_width="0dp"
            android:id="@ id/btn4"
            android:layout_height="93px"
            android:layout_weight="1"
        ></Button>
    </LinearLayout>
  

Ответ №3:

LinearLayout не имеет встроенного понятия «равного интервала». Вы могли бы рассмотреть возможность использования макета, предназначенного для «информационной панели», такого как https://gist.github.com/882650.

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

1. спасибо, это выглядит идеально для этой и другой моей проблемы с макетом. Если бы вы могли уделить минуту, чтобы кратко объяснить, как это реализовать, это было бы здорово. Как только я поместил этот файл в свой apk, что мне делать оттуда?

2. @Max: Смотрите code.google.com/p/iosched/source/browse/android/res/layout/…

3. Первую ссылку, которую вы мне прислали, я должен просто сохранить как com.google.android.apps.iosched.ui.widget со всеми другими моими пакетами в scr, правильно?

4. @Max: Ну, вам нужно быть последовательными. Если вы оставите пакет только в классе Java, его нужно будет включить src/com/google/android/apps/iosched/ui/widget/ в ваш проект, и вы будете ссылаться на него как com.google.android.apps.iosched.ui.widget.DashboardLayout в вашем макете XML. Если вы предпочитаете, вы можете изменить пакет Java, но вам нужно будет изменить каталог и макет, чтобы соответствовать.

Ответ №4:

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

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@ id/LinearLayout" 
   android:layout_height ="wrap_content"
   android:layout_width  ="fill_parent" 
   android:orientation   ="horizontal"
   android:layout_gravity="center_horizontal">

   <Button  
    android:id="@ id/takequiz"  
    android:text="take quiz"
    android:layout_height="93px"
    android:layout_width ="93px" 
    android:layout_marginTop ="30dip"/>

  <Button 
    android:id="@ id/random" 
    android:text="random"
    android:layout_height="93px" 
    android:layout_width ="93px" 
    android:layout_marginTop="30dip"/>

  <Button 
    android:id="@ id/search" 
    android:text="search"
    android:layout_height="93px"
    android:layout_width="93px" 
    android:layout_marginTop="30dip"/>

  <Button
    android:id="@ id/browse"
    android:text="browse"
    android:layout_height="93px" 
    android:layout_width="93px" 
    android:layout_marginTop="30dip" />

 </LinearLayout>
  

Рассматривали ли вы 2 строки? Я сделал аналогичную вещь для приложений типа звуковой платы, используя TableLayout. Хотя в наши дни я больше склоняюсь к использованию RelativeLayout. Вот код таблицы.

 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@ id/LinearLayout" 
   android:layout_height ="fill_parent"
   android:layout_width  ="fill_parent" >
   <TableRow
      android:layout_height ="wrap_content"
      android:layout_width  ="fill_parent" 
      android:gravity       ="center">    
       <Button  
        android:id  ="@ id/takequiz"  
        android:text="take quiz"
        android:layout_height="93px"
        android:layout_width ="93px" />    
      <Button 
        android:id  ="@ id/random" 
        android:text="random"
        android:layout_height="93px" 
        android:layout_width ="93px" />
    </TableRow> 
    <TableRow
      android:layout_height ="wrap_content"
      android:layout_width  ="fill_parent" 
      android:gravity       ="center">    
        <Button 
          android:id  ="@ id/search" 
          android:text="search"
          android:layout_height="93px"
          android:layout_width ="93px" />       
        <Button
          android:id  ="@ id/browse"
          android:text="browse"
          android:layout_height="93px" 
          android:layout_width ="93px"  />
    </TableRow>
 </TableLayout>
  

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

1. это не поместилось на вашем экране? Какой размер вы использовали? А вы были в альбомной ориентации? Если это так, мне, возможно, придется пересмотреть макет.

Ответ №5:

Просто установите поле влево или вправо для любой из кнопок