Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - ConstraintLayout percentage using dimens

There is a question How to make ConstraintLayout work with percentage values? and its answers show how to use the percentages:

<android.support.constraint.Guideline
    android:id="@+id/guideline"
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"/>

But if you don't want to hardcode the percentage but use a dimen resource it does not work.

<!-- inside the layout -->

<android.support.constraint.Guideline
    android:id="@+id/guideline"
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="@dimen/guideline_perc"/>

<!-- inside dimens.xml -->

<dimen name="guideline_perc>0.5</dimen>

You get the following error:

Float types not allowed (at 'guideline_perc' with value 0.5).

If you replace the value with 1, a similar error is returned:

Integer types not allowed (at 'guideline_perc' with value 1).

How do you set a percentage without hardcoding the value into the layout?

like image 245
neits Avatar asked Apr 11 '17 11:04

neits


2 Answers

Instead of using a dimen resource, use an item resource of type dimen:

<item name="guideline_perc" type="dimen">0.5</item>

If using integers, an integer resource would work best:

<integer name="guideline_perc">1</integer>

like image 114
neits Avatar answered Sep 19 '22 13:09

neits


To set a percentage use the fraction syntax

<fraction name="guideline_perc">0.5</fraction>

and then

app:layout_constraintGuide_percent="@fraction/guideline_perc"
like image 32
Catalin Morosan Avatar answered Sep 20 '22 13:09

Catalin Morosan