android - 自定义样式定义的不同Textview的不同格式

标签 android xml styles themes

我在弄清楚如何执行此操作时遇到了问题: 我目前正在编写一个带有不同主题的应用程序(用户可以从不同样式的列表中选择应用程序的完整外观)。 然后选择列表项我要调用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>我可以更改 TextView 的默认外观。 但是如何才能让两个(或更多)不同类型的 TextView 具有不同的应用样式(和通过 xml)?

最佳答案

找到了解决方案(基本上在这个答案 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 时(在重新启动 Activity 后)textviews 开关的外观。像这个方法一样,您可以定义任意多种不同类型的 View 样式,并且只需调用 .setTheme 即可在它们之间切换。

关于android - 自定义样式定义的不同Textview的不同格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8761508/

相关文章:

Android:使用主题/样式更改禁用文本的颜色?

css - 将 CSS 样式分组以备将来使用

java - 带有 xsl 的 xml :sort not sorting

android - android make文件中静态和普通java库之间的区别

Android 计费 - 您拥有此商品时出错

android - windowBackground 上的居中图像与膨胀布局上的图像不同

python - 在Python中解析XML : Multiple same attributes

java - 具有自定义类的 XmlPullParser 不显示所有 RSS 提要

wpf - WPF 中的网格样式没有模板属性?

c# - Xamarin android 保存文本文件