Android中style的使用

时间:2023-03-09 16:14:59
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. super(context, attrs, defStyle);
  4. TypedArray a =   context.obtainStyledAttributes( attrs, R.styleable.TestView, myStyle, 0);
  5. ... ...//这个a中就存放了自定义的属性
  6. }

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

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

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

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

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