Android :Style的使用


Style中文应该是式样,可以使用它指定View的外观,程序的主题等。下面是示例:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <Button  
  8.     android:background="#ff00ffff"  
  9.     android:layout_width="fill_parent"   
  10.     android:layout_height="wrap_content"   
  11.     android:textColor="#ffff0000"  
  12.     android:textSize="18sp"  
  13.     android:text="Hello android"  
  14.     />  
  15. </LinearLayout>  

本来我们定义一个View对象是以这种方式进行的,现在我们应用Style。

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <Button  
  8.     style="@style/buttonstyle"  
  9.     android:text="Hello android"  
  10.     />  
  11. </LinearLayout>  

在res/velues目录下面新建一个style.xml的文件。文件名是任意的,不过必须要以.xml结尾。

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <style name="buttonstyle" parent="@android:style/TextAppearance.Medium">  
  4.         <item name="android:background">#ff00ffff</item>  
  5.         <item name="android:layout_width">fill_parent</item>  
  6.         <item name="android:layout_height">wrap_content</item>  
  7.         <item name="android:textColor">#ff00ffff</item>  
  8.         <item name="android:textSize">18sp</item>  
  9.     </style>  
  10. </resources>  

这两种定义Button的方式实现的效果是一样的。经过比较就可以知道Style'的使用方法。需要注意的是parent 指定了式样的继承。Android预定义了一些式样,通过合理的继承可以减轻我们的工作。上面的方式是继承Android为我们提供的式样,要继承自己定义的式样,方法稍有不同。

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <style name="MyButton.buttonstyle">  
  4.      .............  
  5.     </style>  
  6. </resources>  

它说明buttonstyle继承于MyButton式样,而MyButton是一个自己定义的式样。这种方式是可以递归的。你可以另外定义一个substyle式样让他继承自buttonstyle,那么就是MyButton.buttonstyle.substyle了。

tips:我们为一个View指定了style,那么它会应用这个style。如果我们为一个ViewGroup指定了式样,那么它的Child View是不会继承它的style的。想要让所有的视图都继承一个Style,那就要用到主题Theme了(这句话虽然源自文档,但是强烈质疑这种做法的有效性)。

  • 1
  • 2
  • 下一页

相关内容