2

I'm trying to set a button to 60% height and 60% width of the physical device.

Since the size of the screen is user-dependent, using dips is out of the question.

How can we do percentage height and width in Android? E.g.:

 <Button android:layout_width="60%" android:layout_height="60%"/>
Sophie
  • 47
  • 7

2 Answers2

2

You can use the layout_weight attribute. If you've got the parent layout set to 10 weight, then you can set a weight of 6 in your Button.

There's quite a bit on the topic on Stack Overflow:

Linear Layout and weight in Android

... or on the official Android blog:

http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html

Community
  • 1
  • 1
Michell Bak
  • 13,182
  • 11
  • 64
  • 121
0

Now it's possible with Guidelines positioned with percentage values

Layout Editor

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button"
        app:layout_constraintBottom_toTopOf="@+id/horizontalGuideline"
        app:layout_constraintEnd_toStartOf="@+id/verticalGuideline"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.constraint.Guideline
        android:id="@+id/verticalGuideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.6" />

    <android.support.constraint.Guideline
        android:id="@+id/horizontalGuideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.6" />

</android.support.constraint.ConstraintLayout>
Eugene Brusov
  • 17,146
  • 6
  • 52
  • 68