How can we use percentage values for android view elements? something like this
<TextView
android:id="@+id/"
android:layout_width="75%"
android:layout_height="50%"/>
How can we use percentage values for android view elements? something like this
<TextView
android:id="@+id/"
android:layout_width="75%"
android:layout_height="50%"/>
The support library just added a percent layout.
It can be done like this
https://developer.android.com/reference/android/support/percent/PercentFrameLayout.html
You can use
PercentRelativeLayout
It is a Subclass ofRelativeLayout
that supports percentage based dimensions and margins.To use, you need to add this library to your
Gradle dependency
:Sample structure is
With both
PercentFrameLayout
andPercentRelativeLayout
being deprected in 26.0.0, you need to useConstraintLayout
to size your TextView with percentage values.ConstraintLayout
is really powerful tool to build Responsive UI for Android platform, you can find more details here Build a Responsive UI with ConstraintLayout.Here is the example how to size your TextView(w=75%, h=50%) using ConstraintLayout:
Don't forget to add
constraint-layout
dependency to your modulebuild.gradle
fileOr edit your layout directly in Layout Editor, as shown below:
As a result your
TextView
width is 75% of parent width and height is 50% of parent height:You can use PercentRelativeLayout, It is a recent undocumented addition to the Design Support Library, enables the ability to specify not only elements relative to each other but also the total percentage of available space.
Structure Is
The Percent package provides APIs to support adding and managing percentage based dimensions in your app.
To use, you need to add this library to
your Gradle dependency
list:For demo purpose you can visit Git android-percent-support-lib-sample.
Google has new API called android.support.percent
Example PercentRelativeLayout
UPDATE 2018:
PercentRelativeLayout
andPercentFrameLayout
are deprecated. Consider usingConstraintLayout
Old Answer:
So far Android Support library has limited on where to use this:
with
RelativeLayout
with
FrameLayout
How to use it?
Well, first make sure to include the dependency at
build.grade(Module: app)
Then go to your xml layout in this example (.MainActivity)
For detail please check here: