PercentRelativeLayout Tutorial With Example In Android Studio

PercentRelativeLayout in Android is a subclass of RelativeLayout that supports percentage based margin and dimensions for Views(Button, TextView or any other view).

percent-relative-layout-in-android-studio

Percent Support Library: Percent Support Library provides a feature to set the dimensions and margins in the term of Percentage. It has two pre built Layouts- the PercentRelativeLayout and PercentFrameLayout. In this article we focused on PercentRelativeLayout. This library is pretty easy to use because it has same Relative Layout and FrameLayout that we are familiar with, just with some additional new functionalities.

Important Note –  To use percentrelativelayout you need to add Percent Support Library dependency in build.gradle file.

Gradle Scripts > build.gradle (Module:App) -> inside dependencies

compile 'com.android.support:percent:23.3.0' // Percent Support Library

PercentRelativeLayout Vs Relative Layout In Android:

PercentRelativeLayout class extends from Relative Layout class so it supports all the features, attributes of RelativeLayout and it has percentage dimensions so it also supports some features of LinearLayout. In Simple words we can say that PercentRelativeLayout has features of both Layouts with reduced view complexity.


Need of PercentRelativeLayout In Android

In Android there are lot of Layout’s that can be used at the time of development but at last we always end up with our main three layouts Linear Layout, Relative Layout and FrameLayout. In case if we need to create complex view then we use weight property of LinearLayout to distribute view across screens. But while using weight property we must have noticed that we have to add a default container view to encapsulate our child view . We can follow this approach but it adds an additional view hierarchy in our layout’s which is of no use except holding weight sum value and child view. After the introduction of PercentRelativeLayout we can put percentage dimension and margins to our view that helps us to remove the problem of existing RelativeLayout.


Short Description About RelativeLayout:

Relative Layout is very flexible layout used in android for custom layout designing. It gives us the flexibility to position our component’s based on the relative or sibling component’s position. Just because it allows us to position the component anywhere we want so it is considered as most flexible layout. For the same reason Relative layout is the most used layout after the Linear Layout in Android. It allow its child view to position relative to each other or relative to the container or another container. You can read full tutorial about relative layout.

Important Note: In PercentRelativeLayout, it is not necessary to specify layout_width and layout_height attributes if we specify layout_widthPercent attribute. If in case we want the view to be able to take up more space than what percentage value permits then we can add layout_width and layout_height attributes with wrap_content value. In that case if the size of content is larger than percentage size then it will be automatically resized using wrap_content rule. If we don’t use layout_height and layout_width attribute then android studio shows us an error marker on element in the editor but it will be automatically ignored at run-time.

Basic PercentRelativeLayout XML Code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- Add Child View's Here... -->
</android.support.percent.PercentRelativeLayout>

Attributes of PercentRelativeLayout

Now let’s we discuss some common attributes of a PercentRelativeLayout that helps us to configure it in our layout (xml). It supports all the attributes of RelativeLayout but here we are only discuss some additional attributes.

Very Important Note: Before you use below code make sure you have added Percent Support Library dependency in build.gradle file in depencies.

Gradle Scripts > build.gradle (Module:App) -> inside dependencies

compile 'com.android.support:percent:23.3.0' // Percent Support Library
  • layout_widthPercent: This attribute is used to set the width of the view in percentage. Below we set 50% value for the widthPercent and wrap_content value for the height of the TextView.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.percent.PercentRelativeLayout
        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
            app:layout_widthPercent="50%"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:textSize="20sp"
            android:text="AbhiAndroid" />
    </android.support.percent.PercentRelativeLayout>
    

    percent-relative-layout-width-percent-in-android-studio

  • layout_heightPercent: This attribute is used to set the height of the view in percentage. Below we set 30% value for the heightPercent and wrap_content value for the width of the TextView.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.percent.PercentRelativeLayout 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:layout_width="wrap_content"
            android:text="AbhiAndroid"
            android:textColor="#000"
            android:textSize="20sp"
            app:layout_heightPercent="30%" />
    </android.support.percent.PercentRelativeLayout>
    

    percent-relative-layout-height-percent-in-android-studio

  • layout_marginPercent: This attribute is used to set the margin for view in term of percentage. This attribute set the same margin from all the sides. Below we set wrap_content vlaue for height and width and 10% margin from all the sides of TextView.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.percent.PercentRelativeLayout 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:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="AbhiAndroid"
            android:textColor="#000"
            android:textSize="20sp"
            app:layout_marginPercent="10%" />
    </android.support.percent.PercentRelativeLayout>
    

    percent-relative-layout-margin-percent-in-android-studio

  • layout_marginLeftPercent: This attribute is used to set the percentage margin to the left side of the view. Below we set wrap_content value for height and width and 10% margin to the left side of the TextView.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.percent.PercentRelativeLayout 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:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="AbhiAndroid"
            android:textColor="#000"
            android:textSize="20sp"
            app:layout_marginLeftPercent="10%" />
    </android.support.percent.PercentRelativeLayout>
    

    percent-relative-layout-marginleft-percent-in-android-studio

  • layout_marginTopPercent: This attribute is used to set the percentage margin to the top side of the view.Below we set wrap_content value for height and width and 10% margin to the top side of the TextView.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.percent.PercentRelativeLayout 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:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="AbhiAndroid"
            android:textColor="#000"
            android:textSize="20sp"
            app:layout_marginTopPercent="10%" />
    </android.support.percent.PercentRelativeLayout>
    

    percent-relative-layout-margintop-percent-in-android-studio

  • layout_marginRightPercent: This attribute is used to set the percentage margin to the right side of the view. Below we set wrap_content value for height and width and 10% margin to the right side of the TextView. In this example we set right alignment of TextView so that we can easily check the use of this attribute.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.percent.PercentRelativeLayout 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:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="AbhiAndroid"
            android:textColor="#000"
            android:textSize="20sp"
            android:layout_alignParentRight="true"
            app:layout_marginRightPercent="10%" />
    </android.support.percent.PercentRelativeLayout>
    

    percent-relative-layout-margin-right-percent-in-android-studio

  • layout_marginBottomPercent: This attribute is used to set the percentage margin from bottom side of the view. Below we set wrap_content value for height and width and 10% margin from the bottom side of the TextView. In this example we set bottom alignment of TextView so that we can easily check the use of this attribute.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.percent.PercentRelativeLayout 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:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="AbhiAndroid"
            android:textColor="#000"
            android:textSize="20sp"
            app:layout_marginBottomPercent="10%" />
    </android.support.percent.PercentRelativeLayout>
    

    percent-relative-layout-marginbottom-percent-in-android-studio


PercentRelativeLayout Example In Android Studio:

Below is the example of PercentRelativeLayout in which we create a Login Form with 2 fields user name and Password. In this example we take 2 EditText, 2 TextView and 1 Login Button. For these views we set the dimensions and margin in form of percentage. If a user click on the login Button then a “Thank You” message with user name is displayed on the screen with the help of Toast.

Download Code (Password: abhiandroid) ?

percent-relative-layout-example-in-android-studio
Step 1: Create A New Project And Name It PercentRelativeLayoutExample.

Step 2: Open Gradle Scripts > build.gradle and add Percent Support Library dependency.

apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"
defaultConfig {
applicationId "abhiandroid.percentrelativelayoutexample"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:percent:23.3.0' // Percent Support Library
}

Step 3: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this Step we take 2 EditText‘s, 2 TextView’s and 1 Login Button and for these views we set the dimensions and margin in form of percentage. Note that in all the view’s i didn’t take layout_widht attribute and it still works fine. Android Studio shows a error line on element but it will be automatically ignored at runtime.

<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout 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's for labels and EditText for getting value from user
    -->
    <TextView
        android:id="@+id/txtUserName"
        android:layout_height="wrap_content"
        android:text="UserName :"
        android:textColor="#000"
        android:textSize="20sp"
        app:layout_marginLeftPercent="10%"
        app:layout_marginTopPercent="10%"
        app:layout_widthPercent="30%" />
    <TextView
        android:id="@+id/txtPassword"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtUserName"
        android:text="Password :"
        android:textColor="#000"
        android:textSize="20sp"
        app:layout_marginLeftPercent="10%"
        app:layout_marginTopPercent="4%"
        app:layout_widthPercent="30%" />
    <EditText
        android:id="@+id/userName"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/txtUserName"
        android:hint="User Name"
        android:textColor="#000"
        android:textSize="20sp"
        app:layout_marginLeftPercent="3%"
        app:layout_marginTopPercent="8%"
        app:layout_widthPercent="50%" />
    <EditText
        android:id="@+id/password"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/txtPassword"
        android:hint="Password"
        android:inputType="textPassword"
        android:textColor="#000"
        android:textSize="20sp"
        app:layout_marginLeftPercent="3%"
        app:layout_marginTopPercent="16%"
        app:layout_widthPercent="50%" />
    <!-- Login Button -->
    <Button
        android:id="@+id/login"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_centerHorizontal="true"
        android:background="#F0F"
        android:text="Login"
        android:textColor="#fff"
        android:textSize="20sp"
        app:layout_marginPercent="5%"
        app:layout_widthPercent="60%" />
</android.support.percent.PercentRelativeLayout>

Step 4 : Open src -> package -> MainActivity.java

In this step we open the MainActivity and add the code for initiates the views(EditText and Button). After that we implement setOnClickListener event on login Button so that whenever a user click on Button a thank you message if a user already fill both fields or a error message that enter your user name and password is displayed on the screen with the help of Toast.

package abhiandroid.percentrelativelayoutexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button login;
EditText userName, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// init the View's
userName = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
// perform setOnClickListener Event on Login Button
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// validate user name and password
if (userName.getText().toString().trim().length() > 0 && password.getText().toString().trim().length() > 0) {
// display a thanks you message with user name
Toast.makeText(getApplicationContext(), "Thank You " + userName.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
// display an error message that fill user name and password
Toast.makeText(getApplicationContext(), "Please Enter Your User Name And Password.!!", Toast.LENGTH_SHORT).show();
}
}
});
}
}

Output:

Now run the App and you will login form designed using PercentRelativeLayout.

  • Is this article helps you understand ?
  • YES   NO

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!

Recent Posts

Android-Developer-Money-Ebook-Widget

Download Your FREE Copy!

Download this free eBook and learn: 
1. Different approach developer use to earn through App business
2. Learn how Android Developer can generate passive income
3. Job is not the only option and you can choose freelancing

close-link

JUST ONE MORE STEP TO COMPLETE...

Enter your email to get FREE exclusive Android email tips and tutorials:
SEND ME THE UPDATE >>
We hate SPAM and promise to keep your email address safe.
close-link
Download Your FREE Copy!

Download this free eBook and learn: 
1. Different approach developer use to earn through App business
2. Learn how Android Developer can generate passive income
3. Job is not the only option and you can choose freelancing

close-link

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!

Join over 5056 Android developers in our community and get access to this free eBook now!
close-link

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!
close-link

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!

Join over 5056 Android developers in our community and get access to this free eBook now!
close-link

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!
close-link

Struggling with Android Material Design?

Download this FREE eBook and master learning of Android Material Design!
close-link
Master Android Material Design ^