【问题标题】:Android - use attributes to tweak custom stylesAndroid - 使用属性来调整自定义样式
【发布时间】:2012-03-20 12:12:55
【问题描述】:

这是我的问题。我在相关的 .xml 文件中定义了自定义主题和样式,以便自定义各种视图。以下是一些代码摘录:

主题.xml:

...
<style name="Legacy" parent="android:Theme.NoTitleBar">
    <item name="android:buttonStyle">@style/Legacy.Button</item>
    ...
</style>

styles.xml:

...
<style name="Legacy.Button" parent="@android:style/Widget.Button">
    <item name="android:textColor">#ffffff</item>
    <item name="android:background">@drawable/button_selector_blue</item>
    <item name="android:textSize">15dp</item>
</style>

假设我将应用程序的主题设置为 Legacy。如果我在布局中使用 Button,它将获得我的自定义默认参数(白色文本、背景是 @drawable/button_selector_blue 等)。

现在假设我想保留这些参数以保留文本大小:我想要一些文本大小更大的按钮,这将在 attrs.xml 的 titleSize 属性中定义:

...
<attr name="titleSize" format="reference|dimension" />

以及在我的themes.xml 文件中为每个主题设置了哪个值。

所以我的布局将包含如下内容:

<Button 
    android:id="@+idmyButtonId"
    android:drawableRight="@drawable/aDrawable" 
    android:text="@string/someText"
    android:textSize="?titleSize"
    android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>

启动我的应用程序时,我收到以下错误: java.lang.UnsupportedOperationException:无法转换为维度:type=0x2

所以看来我不能使用属性来调整自定义样式——至少不能这样。这样的事情可能吗?如果没有,你会用什么来达到这样的效果?

我想让用户能够在不同的主题中进行选择,所以我不能只定义一个额外的 ButtonWithLargeText 样式并直接在我的布局中使用它。

感谢您的帮助!

【问题讨论】:

标签: android attributes styles themes


【解决方案1】:

我终于让它工作了。我没有在 attrs.xml 中定义标题的大小,而是使用了dimens.xml。所以现在以下工作:

<Button 
  android:id="@+idmyButtonId"
  android:drawableRight="@drawable/aDrawable" 
  android:text="@string/someText"
  android:textSize="@dimen/titleSize"
  android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>

虽然我通过以下方式在 Button 上获得常规文本大小(我在 styles.xml 中定义):

<Button 
    android:id="@+id/idRegularButton"
    android:text="@string/regularSizeText"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
</Button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 2011-01-11
    • 1970-01-01
    • 2011-12-12
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    相关资源
    最近更新 更多