Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margin/Padding in percentage in XML

Tags:

android

layout

I am new in android development. I want to set margin & padding in Xml,not in dp or px but in percentage. Is there any way to do this?

like image 746
Himanshu Dudhat Avatar asked Jun 29 '12 05:06

Himanshu Dudhat


2 Answers

it is not possible, though You better do it by taking width and height of screen like below in your java code, and

 Display display = getWindowManager().getDefaultDisplay(); 
 int width = display.getWidth();
 int height = display.getHeight();

then calculate your margin from screen size, and set it by

  setmargin(int x) //method of view/layout.

this way you can set margin depending on the screen size not fixed for all screen, and basically it is like setting in percentage but from Java code.

like image 132
AAnkit Avatar answered Sep 22 '22 10:09

AAnkit


It became possible with Guidelines introduced in ConstraintLayout.

Here's the example of TextView placed at 60% of screen width and 25% of screen height:

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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintLeft_toLeftOf="@+id/guideline1"
        app:layout_constraintTop_toTopOf="@+id/guideline2" />

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

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

</android.support.constraint.ConstraintLayout>
like image 25
Eugene Brusov Avatar answered Sep 23 '22 10:09

Eugene Brusov