Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Layout width equal height

Is there a method to have the height depending from the width in my xml?

I have some Buttons in a linear layout. The button's widths depending from the device because they fill the screen horizontally. I want to have square buttons and this is my problem. Is there one can help me?

<Button
            android:id="@+id/b_0xa"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:clickable="false"
            android:text="@string/b_0xa" />
like image 283
Twing90 Avatar asked Jan 26 '13 19:01

Twing90


People also ask

What is layout width?

Android layout Width & HeightThis property is used to set the width of the given control. According to content the width has been changed. Fill_parent:- fill_parent will take the width according to the container in which we added button. We can also set it in pixel like 200px etc..

What is Layout_constraintdimensionratio?

A ConstraintLayout is a ViewGroup which allows you to Position and size Views in a flexible way. It is basically RelativeLayout on Steriods. The Views will be positioned and sized w.r.t other Views with the Use of Constraints.

What is the image view in Android?

ImageView class is used to display any kind of image resource in the android application either it can be android. graphics. Bitmap or android.


1 Answers

To make the height of view equals to width of view, can use ConstraintLayout

 app:layout_constraintDimensionRatio="1:1"

1 before : is for width

1 after : is for height

Please try below code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:text="Button"/>

</androidx.constraintlayout.widget.ConstraintLayout>

The output of above code is:

enter image description here

like image 131
Android Geek Avatar answered Sep 17 '22 14:09

Android Geek