继承与android风格

时间:2013-05-28 06:13:01

标签: android android-layout android-styles

我已为TextView为contentBg样式定义了红色。我可以通过从父样式更改或重命名样式名称myContentNew将TextView颜色红色更改为蓝色吗?不应更改TextView样式名称contentBG。它是否有可能在android sytle中。

<RelativeLayout 
   style="@style/myContent"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">
<TextView 
   style="@style/contentBG"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"/>
</RelativeLayout>

我的代码应该如下

<RelativeLayout 
       style="@style/myContentNew"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content">
    <TextView 
       style="@style/contentBG"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"/>
 </RelativeLayout>

您可以通过我附加的图片获得清晰的想法。enter image description here

喜欢CSS:

.myContent .contentBg{background-color:red}
.myContentNew .contentBg{background-color:blue}

由于

2 个答案:

答案 0 :(得分:1)

我不敢。

设置contentBG样式后。它不能改变,但在代码中。

答案 1 :(得分:1)

以下是创建2个不同主题的示例:

首先需要修改清单文件以调用默认的自定义主题,例如:

<application
    android:name="RateDayApplication"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/CustomTheme" >

然后,在styles.xml文件中,准备2个不同的主题,包含相同的样式contentBG

<!-- *** THEME WITH RED BG*** -->
<style name="CustomTheme" parent="@android:style/Theme.Holo.Light">
    <item name="contentBG">@style/contentBGred</item>

</style>

<style name="contentBGred" >
    <item name="android:colorBackground">@color/red</item>
</style>

<!-- *** THEME WITH BLUE BG*** -->
<style name="CustomThemeNew" parent="@android:style/Theme.Holo.Light">
    <item name="contentBG">@style/contentBGblue</item>
</style>

<style name="contentBGblue" >
    <item name="android:colorBackground">@color/blue</item>
</style>

重要提示:此处我使用Theme.Holo.Light作为父主题,如果您使用其他主题,则可以更改它。

在上面的2个主题中,样式具有相同的名称,它将用作XML文件中的引用。要声明此引用,您必须将其添加到attrs.xml文件夹下的无标题values文件中。

以下是内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <attr name="contentBG" format="reference" />
</resources>

完成后,您只需要在XML文件中以这种方式调用此样式(您不再需要布局上的样式):

<RelativeLayout 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">
<TextView 
   style="?contentBG"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"/>
</RelativeLayout>

此处的问号表示将使用引用加载样式。将使用的样式将是Activity上应用的当前主题之一。

您可以使用以下方式轻松设置活动所需的主题:

setTheme(R.style.CustomTheme);

setTheme(R.style.CustomThemeNew);
相关问题