【问题标题】:How to set button layout_constraintWidth_percent in styles.xml?如何在styles.xml中设置按钮layout_constraintWidth_percent?
【发布时间】:2019-11-15 09:56:16
【问题描述】:

我需要我的应用程序的所有按钮都具有相同的宽度和高度。所以我尝试在styles.xml中这样做:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:buttonStyle">@style/MyButton</item>
</style>

<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="layout_constraintHeight_percent">0.15</item>
    <item name="layout_constraintWidth_percent">0.23</item>
</style>

它不起作用,按钮忽略了这些值。如何实现?

而且,一旦我实现了它,我怎样才能覆盖一些我需要更大的特定按钮的值?

【问题讨论】:

  • 你也可以发布按钮 XMl 代码
  • 你不应该在styles.xml中定义宽度/高度

标签: android android-layout android-constraintlayout android-button android-styles


【解决方案1】:

您需要为每个受影响的按钮将以下内容添加到 XML 中:

style="@style/MyButton"

这是为什么呢?该按钮使用属性android:buttonStyle 来设置自己的样式。您要更改的值与布局有关,与按钮不直接相关,但与 ConstraintLayout 相关。

在布局期间,ConstraintLayout 不会查看主题中设置的android:buttonStyle 属性,因此它会错过您在按钮样式中设置的值。 style="@style/MyButton" 将按钮样式中的值强制转换为布局考虑的属性,并且按钮将随您的更改一起出现。

显式设置样式不是那么干净,但它会起作用。

【讨论】:

    【解决方案2】:

    您需要将按钮的高度和宽度设置为 0dp 才能正常工作。

    当您需要更大的按钮时,您可以在该按钮中使用百分比属性,这样它将忽略样式百分比约束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多