简体   繁体   中英

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?

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>

To set a percentage use the fraction syntax

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

and then

app:layout_constraintGuide_percent="@fraction/guideline_perc"

Now in 2021 dimen float works fine. Just autocompletion in Android studio in that case doesn't. Don't know why.

app:layout_constraintGuide_percent="@dimen/guideline_perc"

由系统本身生成

 <item name="porcent_line_top_navebar" type="dimen" format="float">0.88</item>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM