Как сделать изображение/кнопку идеальной квадратной формы

Я разрабатываю базовую SUDOKO GAME для Android. Мне нужна таблица 4x4 со всеми ячейками в виде квадратов.

Я пытаюсь сделать это с помощью 16 кнопок в файле TableLayout.

Мой путь выглядит так

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

они прямоугольной формы :(

мой xml

<TableLayout
android:id="@+id/tl"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center" >

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:gravity="center" >

    <Button
        android:id="@+id/button1"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:id="@+id/button2"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="2" />

    <Button
        android:id="@+id/button3"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="3" />

    <Button
        android:id="@+id/button4"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="4" />
</TableRow>

<TableRow
    android:id="@+id/tableRow2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center" >

    <Button
        android:id="@+id/button5"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="5" />

    <Button
        android:id="@+id/button6"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="6" />

    <Button
        android:id="@+id/button7"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="7" />

    <Button
        android:id="@+id/button8"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="8" />
</TableRow>

<TableRow
    android:id="@+id/tableRow3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center" >

    <Button
        android:id="@+id/button9"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="9" />

    <Button
        android:id="@+id/button10"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="7" />

    <Button
        android:id="@+id/button11"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="8" />

    <Button
        android:id="@+id/button12"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="7" />
</TableRow>

<TableRow
    android:id="@+id/tableRow3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center" >

    <Button
        android:id="@+id/button13"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="9" />

    <Button
        android:id="@+id/button14"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="7" />

    <Button
        android:id="@+id/button15"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="8" />

    <Button
        android:id="@+id/button16"
        style="@style/box_sky_blue"
        android:layout_weight="1"
        android:text="7" />
</TableRow>
</TableLayout>

вот коробка небесно-голубая

<style name="box_sky_blue">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:background">@color/box_color_sky_blue</item>
    <item name="android:layout_margin">5dp</item>
    <item name="android:padding">5dp</item>
    <item name="android:textSize">20sp</item>
    <item name="android:gravity">center</item>
    <item name="android:textColor">#ffffff</item>
</style>

Как сделать их квадратными, так как у меня есть квадрат 4x4,5x5 и 6x6


person Maveňツ    schedule 24.07.2014    source источник
comment
можете ли вы опубликовать код box_sky_blue.xml из стиля   -  person Android is everything for me    schedule 24.07.2014
comment
@Androidiseverythingforme, пожалуйста, просмотрите :)   -  person Maveňツ    schedule 24.07.2014
comment
если вы используете макет ограничения, а высота установлена ​​​​на 0 dp, установите ширину на 0 dp и используйте это приложение: layout_constraintDimensionRatio = H, 1: 1   -  person Abdulrahman Abdelkader    schedule 23.07.2020
comment
@AbdulrahmanAbdelkader 4 года назад макет ограничений не был введен в SDK, он появился в 2018 году.   -  person Maveňツ    schedule 24.07.2020


Ответы (3)


Измените wrap_contents на размер по умолчанию:

android:layout_width="wrap_content"
android:layout_height="wrap_content"

to

android:layout_width="@dimen/box_size"
android:layout_height="@dimen/box_size"

(а затем установите box_size в res/values/dimen.xml, например: <dimen name="box_size">50dp</dimen>)


ИЛИ используйте wrap_content для ширины, а затем в коде используйте myBox.setHeight(myBox.getMeasuredWidth);, чтобы ширина и высота совпадали. Просто убедитесь, что представление полностью загружено, иначе getMeasuredWidth вернет 0.

РЕДАКТИРОВАТЬ:

Чтобы изменить высоту в соответствии с шириной wrap_content после загрузки представления, вы можете использовать ViewTreeObserver:

if(yourActivityLayout.getViewTreeObserver().isAlive()){
    yourActivityLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout(){
            // The view is completely loaded now, so getMeasuredWidth() won't return 0
            yourButton1.setLayoutParams(new TableLayout.LayoutParams(yourButton1.getMeasuredWidth(), yourButton1.getMeasuredWidth()));
            ... // Do this for all buttons (preferably in a for-loop to prevent repetition)

            // Destroy the onGlobalLayout afterwards, otherwise it keeps changing
            // the sizes non-stop, even though it's already done
            yourActivityLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
}
person Kevin Cruijssen    schedule 24.07.2014

Код кнопки в XML

<Button
    android:id="@+id/btn"  
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:background="@drawable/buttonshape"/>

код кнопки shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
 android:shape="rectangle" >
<corners
android:topLeftRadius="0dp"
android:topRightRadius="0dp"
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp"/>
<solid
android:color="#0000ff"/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"/>
<size
android:width="64dp"
android:height="64dp"/>
</shape>
person Android is everything for me    schedule 24.07.2014
comment
это жестко запрограммировано. Вы должны предоставить решение, которое не является жестко запрограммированным. - person Yash Jain; 01.09.2020

Попробуйте добавить фиксированную ширину и высоту.

 android:layout_width="@dimen/box_size"
 android:layout_height="@dimen/box_size"

и в res/values/dimen.xml добавить

 <dimen name="box_size">40dp</dimen>
person nayana bhoj    schedule 23.01.2017