This is achievable without any code by using weights in a LinearLayout
, as follows:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="10"
android:orientation="horizontal">
<ProgressBar
android:layout_widthPercent="0dp"
android:layout_heightPercent="wrap_content"
android:weight="1"/>
</LinearLayout>
And because the parent has a total sum of 10 units and the child will only take 1 of those, the child will actually have 10% of the parent's width.
It is also possible to use the power of the support library through the PercentRelativeLayout. The basic usage is as follows:
<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">
<ProgressBar
app:layout_widthPercent="50%"
app:layout_heightPercent="wrap_content"
app:layout_marginTopPercent="10%"/>
</android.support.percent.PercentRelativeLayout>
To add it to your project, you will need to include the percent
support library in your project. To do so, include the following line in your build.gradle
file
compile 'com.android.support:percent:{lastest_support_library_version}'