android style与主题

来源:互联网 发布:淘宝女装店铺装修素材 编辑:程序博客网 时间:2024/05/21 21:44

在我们展现控件的过程中,我们会对控件进行属性的设置.然而,在我们设置属性的过程中,也许,会有大量的属性是重复的.那么,如何才能解决我们代码冗余的问题.我们想起了web开发工程中的css思想.在android中,如果要做到这一点,我们可以使用style,所谓style,也就是属性的组合.将属性组合在一起被引用,达到特定的效果.
当然,也是为了重复利用,减少代码的编写,提高维护.

接下来,我们来看如何实现:

在我们的res目录下,存在values目录.在该目录下,存在style.xml文件,该文件是我们编写style属性的地方.

例如:

<style name="btn_style">        <item name="android:textColor">@drawable/text_selector</item>        <item name="android:background">@drawable/btn_selector</item></style>

text_selector 文件

<selector xmlns:android="http://schemas.android.com/apk/res/android" >    <item android:state_pressed="true" android:color="@color/red"></item>    <item android:state_pressed="false" android:color="@color/white"></item></selector>

btn_selector文件

<selector xmlns:android="http://schemas.android.com/apk/res/android" >     <!-- 当被选中的时候 -->    <item android:state_selected="true"        >        <shape >             <gradient android:angle="270" android:endColor="#99BD4C"                   android:startColor="#A5D245" />               <size android:height="60dp" android:width="320dp" />               <corners android:radius="8dp" />          </shape>    </item>      <!-- 当被按下的时候 -->      <item android:state_pressed="true">          <shape >              <gradient android:angle="270" android:endColor="#99BD4C"                   android:startColor="#A5D245"/>               <size android:height="60dp" android:width="320dp" />               <corners android:radius="8dp" />             </shape>      </item>      <!-- 其他情况 -->        <item >            <shape >                <gradient android:angle="270" android:endColor="#A8C3B0"                   android:startColor="#C6CFCE"  />               <size android:height="60dp" android:width="320dp" />               <corners android:radius="8dp" />            </shape>        </item></selector>

编写了style,然后我们在布局文件的控件上引用此style:

 <Button      style="@style/btn_style"      android:layout_alignParentBottom="true"      android:layout_alignParentLeft="true"      android:layout_marginBottom="195dp"      android:text="@string/hello_world" />

这样,就达到了我们展现的目的,然后,我们可以将该style设置到不同的控件中
,然后在所有的控件中都可以使用.

在这里,style还可以被继承,子类的style会拥有父类style的全部属性.

<style name="style_margin_top" parent="style_color_base">    <item name="android:layout_marginTop">123dp</item></style>

我们的style还可以继承提供的style,提供给我们使用.

    <style name="style_one" parent="@android:style/Animation.Dialog"></style>

主题:所谓主题,其实是一种特殊的style,这些style主要应用于
Activity与Application中而已.

    <activity        android:theme="@android:style/DeviceDefault.SegmentedButton"        android:name="com.example.mystyleandtheme.MainActivity"        </intent-filter>    </activity>
0 0