在android開發中,往往要用到自定義的控件來實現我們的需求或效果。在使用自定義
控件時,難免要用到自定義屬性,那怎么使用自定義屬性呢?
在文件res/values/下新建attrs.xml屬性文件,中定義我們所需要的屬性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?xml version= "1.0" encoding= "utf-8" ?> <resources><!-- resource是跟標簽,可以在里面定義若干個declare-styleable --> <declare-styleable name= "custom_view" ><!-- name定義了變量的名稱 --> <attr name= "custom_color" format= "color" ></attr> <!-- 定義對應的屬性,name定義了屬性的名稱 --> <attr name= "custom_size" format= "dimension" ></attr> <!--每一個發生要定義format指定其類型,類型包括 reference 表示引用,參考某一資源id string 表示字符串 color 表示顏色值 dimension 表示尺寸值 boolean 表示布爾值 integer 表示整型值 float 表示浮點值 fraction 表示百分數 enum 表示枚舉值 flag 表示位運算 --> </declare-styleable> |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class customtextview extends textview { private int textsize; //自定義文件大小 private int textcolor; //自定義文字顏色 //自定義屬性,會調用帶兩個對數的構造方法 public customtextview(context context, attributeset attrs) { super (context, attrs); typedarray ta = context.obtainstyledattributes(attrs, r.styleable.custom_view); //typedarray屬性對象 textsize = ta.getdimensionpixelsize(r.styleable.custom_view_custom_size, 20 ); //獲取屬性對象中對應的屬性值 textcolor = ta.getcolor(r.styleable.custom_view_custom_color, 0x0000ff ); setcolorandsize(textcolor, textsize); //設置屬性 ta.recycle(); } public customtextview(context context) { super (context); } private void setcolorandsize( int textcolor, int textsize) { settextcolor(textcolor); settextsize(textsize); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" xmlns:ldm= "http://schemas.android.com/apk/res/com.ldm.learn" android:layout_width= "match_parent" android:layout_height= "match_parent" android:background= "#f6f6f6" android:orientation= "vertical" android:padding= "10dp" > <com.ldm.learn.customtextview android:layout_width= "100dp" android:layout_height= "100dp" android:text= "自定義textview" ldm:custom_color= "#333333" ldm:custom_size= "35sp" /> </linearlayout> |
布局說明:
通過以上幾步就可以實現我們想要的自定義屬性效果(用自定義屬性設置文字大小及顏色)啦!