Android中style的使用

摘自搜搜问问。

<item name="#1">#2</item>
1.item 的name属性#1可以为所有系统所带组件的属性,#2为此属性的值如android:layout_height  android:layout_width  android:background都可写成如下形式   <item name="android:background">#000000</item>
2.除此之外可以是任意你自己定义的属性 如: <item name="myKey">myValue</item>不同之处在于<item name="android:background">#000000</item>由于是系统自带属性,所以可以直接在其他view 的属性中引用此style. 自定义的属性要经过两个步骤才可以使用.

A.values目录下创建一个attrs.xml文件,以如下方式声明 <attr name="myname" format="String" />

B.在一个style的item中以如下方式引用 <item name="myname">"我的名字"</item>

C.经过上两步就可以在自己的View中使用

 
  1. MyView(Context context, AttributeSet attrs,int myStyle)    
  2.   
  3. {           
  4.   
  5.          super(context, attrs, defStyle);               
  6.   
  7.          TypedArray a =   context.obtainStyledAttributes( attrs, R.styleable.TestView, myStyle, 0);     
  8.   
  9.          ... ...//这个a中就存放了自定义的属性   
  10.   
  11. }   

这是最重要的三步,建议先不用自定义属性,熟悉好怎样利用系统自带的属性来统一风格和布局,使用系统属性的方法如下:

    一.values目录下创建styles.xml,代码如下:  

    

 
  1. <resources>      
  2.   
  3.         <style name="My" parent="android:Widget">      
  4.   
  5.              <item name="android:background">颜色值</item>     
  6.   
  7.         </style>      
  8.   
  9. </resources>  

二.因为是系统属性,直接就可以在任意一个view中使用了

 
  1. <TextView      
  2.      style="@style/My"     
  3.      android:layout_width="wrap_content"     
  4.      android:layout_height="wrap_content"/>    
   


作者:KillerLegend
出处:http://www.cnblogs.com/KillerLegend/
分享最新的资源,分享个人所得,欢迎关注我的新浪微博
新浪微博主页:ikey4u
我的个人博客:www.ikey4u.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 
原文地址:https://www.cnblogs.com/killerlegend/p/3352634.html