Android - ConstraintLayout percentage using dimens

Deadly 提交于 2019-12-12 10:36:23

问题


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?


回答1:


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>




回答2:


To set a percentage use the fraction syntax

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

and then

app:layout_constraintGuide_percent="@fraction/guideline_perc"


来源:https://stackoverflow.com/questions/43345082/android-constraintlayout-percentage-using-dimens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!