Android 中style的使用

来源:互联网 发布:linux最新内核编译 编辑:程序博客网 时间:2024/06/05 10:41

Style的作用简单讲就是使布局中的一些控件有相同的显示风格,而且不用重复的在控件中定义他们的属性。

或者说对控件的一种格式化的输出,使功能相近的控件有一致的对外表现形式,而且不用重复的复制代码。


使用Style
在控件的定义中添加 :style=”@style/btn_style_1”
同时在文件夹 res/values/style.xml 添加一个 btn_style_1项 即可。

例如: Button 中使用了style=”@style/btn_style_1”的属性

        <Button            android:id="@+id/btn4"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginTop="10dp"            android:layout_marginLeft="5dp"            android:focusable="true"            android:text="Test 4"             android:layout_weight="1"            style="@style/btn_style_1"/>

同时styles.xml中给出btn_style_1的定义,其中也是定义了一下控件的属性,如果其他的控件需要和Button 1有一样的显示风格就可以直接使用了。

<resources>    <style name="btn_style_1">        <item name="android:layout_width">fill_parent</item>        <item name="android:layout_height">wrap_content</item>        <item name="android:textColor">#ffffff</item>        <item name="android:gravity">center</item>        <item name="android:textStyle">italic</item>        <item name="android:shadowColor">#ffffff</item>        <item name="android:shadowDx">1</item>        <item name="android:shadowDy">1</item>        <item name="android:shadowRadius">5</item>        <item name="android:background">@drawable/btn_style_1_selector</item>    </style></resources>    

注: 其中 android:background属性中用到了 btn_style_1_selector,它是定义在 res/drawable文件夹中的一个xml 文件,它可以描述当按钮按下时和正常时的显示风格。
例如: 它可以在按钮按下时/正常时 显示不同的图片。

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/btn_add_accounts_pressed" android:state_pressed="true"/>    <item android:drawable="@drawable/btn_add_accounts_normal"/></selector>

这里总结了一些按钮的style,以备开发时使用。

这里写图片描述

工程代码

0 0
原创粉丝点击