2015-08-09 3 views
0

Я пытаюсь создать кнопки букв в относительной компоновке. Основная проблема заключается в том, что я не могу установить кнопки, чтобы сохранить соотношение сторон 1: 1 и отобразить их на экране.Относительная установка кнопок сетки Android

Это то, что я хочу добиться:

enter image description here

Кнопки должны всегда быть 1: 1 и текст рупор старт с кнопкой посередине. До сих пор я пробовал использовать сетку и пуговицы в 5х5 размалывания. Но если я устанавливаю кнопку ш/к, скажем, 50dp на некоторых дисплеях я могу видеть только ABC и половину D.

Также я пытался поставить на LinearLayout как:

<RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_above="@id/adSponsor" 
    android:layout_below="@id/barSearch" 
    android:layout_margin="20dp"> 

    <LinearLayout 

     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" 
     android:orientation="vertical"> 

     <LinearLayout 
      android:id="@+id/buttonPanel" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 

      <Button 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_margin="5dp" 
       android:layout_weight="1" 
       android:background="@drawable/letter_button" 
       android:gravity="center|top" 
       android:text="A" 
       android:textAlignment="gravity" 
       android:textColor="@color/red" 
       android:textSize="@dimen/letter_box_text" 
       android:textStyle="bold" /> 

      <Button 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_margin="5dp" 
       android:layout_weight="1" 
       android:background="@drawable/letter_button" 
       android:gravity="center|top" 
       android:text="B" 
       android:textAlignment="gravity" 
       android:textColor="@color/red" 
       android:textSize="@dimen/letter_box_text" 
       android:textStyle="bold" /> 

      <Button 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_margin="5dp" 
       android:layout_weight="1" 
       android:background="@drawable/letter_button" 
       android:gravity="center|top" 
       android:text="C" 
       android:textAlignment="gravity" 
       android:textColor="@color/red" 
       android:textSize="@dimen/letter_box_text" 
       android:textStyle="bold" /> 

      <Button 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_margin="5dp" 
       android:layout_weight="1" 
       android:background="@drawable/letter_button" 
       android:gravity="center|top" 
       android:text="D" 
       android:textAlignment="gravity" 
       android:textColor="@color/red" 
       android:textSize="@dimen/letter_box_text" 
       android:textStyle="bold" /> 

      <Button 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_margin="5dp" 
       android:layout_weight="1" 
       android:background="@drawable/letter_button" 
       android:gravity="center|top" 
       android:text="E" 
       android:textAlignment="gravity" 
       android:textColor="@color/red" 
       android:textSize="@dimen/letter_box_text" 
       android:textStyle="bold" /> 

     </LinearLayout> 

    </LinearLayout> 

</RelativeLayout> 

Но в этом случае кнопки не имеют соотношение сторон 1: 1.

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

+0

Но ... где ** Y **? –

+0

Вместо этого ужасного размещения макетов (сильно обескураженный) ... почему вы не используете GridLayout? Или, в качестве альтернативы, RelativeLayout с GridView? –

ответ

2

Для того, чтобы получить квадратную кнопку, я хотел бы предложить вам подкласс Button класса и переопределить метод onMeasure:

public class SquareButton extends Button { 
    public SquareButton(Context context) { 
     super(context); 
    } 

    public SquareButton(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public SquareButton(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
    public SquareButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     int width = MeasureSpec.getSize(widthMeasureSpec); 
     int height = MeasureSpec.getSize(heightMeasureSpec); 
     if(width > height) { 
      super.onMeasure(heightMeasureSpec, heightMeasureSpec); 
     } else { 
      super.onMeasure(widthMeasureSpec, widthMeasureSpec); 
     } 
    } 
} 

Для того, чтобы получить равномерное пространство между кнопками, я бы так с подходом LinearLayout и layout_weight, установленным на Buttons. Вы можете пропустить установку weightSum на родительском, если количество кнопок в строке является переменной. Для того чтобы нижняя часть буквы начиналась с середины кнопки, возможно, стоит попробовать, чтобы увидеть, можете ли вы сопоставить свойство paddingBottom объекта Button с textSize. Если нет, я думаю, вам придется переопределить метод onDraw.

0

Ass это в горизонтальной LinearLayout:

android:weightSum="5" 

И это в ваших кнопок:

android:layout_weight="1" 

Это предполагает, что у вас есть 5 кнопок в каждой строке.

0

Как указано в @iTurki, вы должны использовать комбинации weightSum и layout_weight, чтобы равномерно распределять виды по линейной линии. Сказав это, я понимаю, что вам все равно нужно отображать ваших персонажей в квадратных квадратах. Для этого вы можете использовать RelativeLayout, содержащую ImageViews, и использовать ImageView в качестве кнопок clickable.

Преимущество ImageView заключается в том, что вы можете установить прозрачное квадратное изображение в качестве фона и использовать android:adjustViewBounds="true", чтобы высота изображения увеличивалась/уменьшалась в соответствии с пространством горизонтальной ширины, доступным для изображения. ваш макет должен выглядеть примерно так.

<LinearLayout 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:orientation="horizontal" 
android:weightSum="5" 
> 
<RelativeLayout 
android:layout_width="0dp" 
android:layout_weight="1" 
android:layout_height="wrap_content" 
> 
<ImageView 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:adjustViewBounds="true" 
android:src="square_transparent_Image.png" 
/> 
<TextView 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:gravity="center" 
android:textAlignment="center" 
android:text="A" 
/> 
</RelativeLayout> 
<RelativeLayout 
android:layout_width="0dp" 
android:layout_weight="1" 
android:layout_height="wrap_content" 
> 
<ImageView 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:adjustViewBounds="true" 
android:src="square_transparent_Image.png" 
/> 
<TextView 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:gravity="center" 
android:textAlignment="center" 
android:text="B" 
/> 
</RelativeLayout> 
<RelativeLayout 
android:layout_width="0dp" 
android:layout_weight="1" 
android:layout_height="wrap_content" 
> 
<ImageView 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:adjustViewBounds="true" 
android:src="square_transparent_Image.png" 
/> 
<TextView 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:gravity="center" 
android:textAlignment="center" 
android:text="C" 
/> 
</RelativeLayout> 
<RelativeLayout 
android:layout_width="0dp" 
android:layout_weight="1" 
android:layout_height="wrap_content" 
> 
<ImageView 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:adjustViewBounds="true" 
android:src="square_transparent_Image.png" 
/> 
<TextView 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:gravity="center" 
android:textAlignment="center" 
android:text="D" 
/> 
</RelativeLayout> 
<RelativeLayout 
android:layout_width="0dp" 
android:layout_weight="1" 
android:layout_height="wrap_content" 
> 
<ImageView 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:adjustViewBounds="true" 
android:src="square_transparent_Image.png" 
/> 
<TextView 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:gravity="center" 
android:textAlignment="center" 
android:text="E" 
/> 
</RelativeLayout> 
</LinearLayout> 
Смежные вопросы