【问题标题】:Different formats for different Textview defined by Custom style自定义样式定义的不同Textview的不同格式
【发布时间】:2012-02-04 09:34:59
【问题描述】:

我无法弄清楚如何执行此操作: 我目前正在编写一个带有不同主题的应用程序(用户可以从不同样式的列表中选择应用程序的完整外观)。 然后列表项被选中我想调用setTheme(R.style.Own_App_Style0);来改变完整的外观。

这个问题最好用一个例子来解释: 假设我们有 2 个 TextView。

主题1 1. TextView:TextColor 应该是绿色,TextSize 15sp。 2. TextView:TextColor 应该是红色,TextSize 10sp。

主题2 1. TextView:TextColor 应该是蓝色,TextSize 10sp。 2. TextView:TextColor 应该是黄色,TextSize 10sp。

当然我知道通过设置<item name="textViewStyle">@android:style/Widget.TextView</item> 可以改变TextViews 的默认外观。 但是如何让我们说两种(或更多)不同类型的 TextView 具有不同的应用样式(以及通过 xml)?

【问题讨论】:

  • 查看这个问题的答案:stackoverflow.com/questions/4630440/…
  • 不完全是。我想稍后在程序中只调用 setTheme(R.style.OwnAppStyle);更改完整的布局。当它们发生时,不要有问题地更改单独的小部件。我将此添加到问题中。

标签: android xml styles themes


【解决方案1】:

找到了解决方案(基本上在这个答案setTextAppearance through code referencing custom attribute)。万一其他人有这个问题,我会简短地解释一下:

在 style.xml 中声明一个属性,并在实际的样式定义中为该属性分配一个值(引用):

<declare-styleable name="CustomTextView">
    <attr name="mainTextView" format="reference"/>            
</declare-styleable>

<style name="appstyle0" parent="android:style/Theme.Holo.Light">
    <item name="@attr/mainTextView">@style/CustomTextViewAppearance1</item>
    <item name="android:textViewStyle">@style/CustomTextViewAppearance2</item>
</style>

<style name="appstyle1" parent="android:style/Theme.Holo.Light">
    <item name="@attr/mainTextView">@style/CustomTextViewAppearance2</item>
    <item name="android:textViewStyle">@style/CustomTextViewAppearance1</item>
</style>
<style name="CustomTextViewAppearance1">
    <item name="android:textSize">10dip</item>
</style>
<style name="CustomTextViewAppearance2">
    <item name="android:textSize">30dip</item>
</style>

现在在布局中所有的textViews都像CustomTextViewAppearance2(因为这是这种风格的标准设置。应该使用其他风格的textViews写入定义:

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="blablabla"  
            style="?mainButtonTextView"/>

当您现在调用 .setTheme(重新启动活动后)时,textviews 开关的外观。像这种方法一样,您可以定义尽可能多的不同类型的 View 样式,并且只需调用 .setTheme 即可在它们之间切换。

【讨论】:

  • 谢谢,这对我有帮助!一开始我期待有一个类似“选择器”的东西:10dip
【解决方案2】:

不幸的是,样式一旦被定义就是静态的。要以编程方式修改整个级联样式,您必须更改样式本身的定义。相反,您所能做的就是更改分配给 TextView(或任何可设置样式的对象)的样式,如我在上面的评论中链接到的问题中所述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多