一、簡(jiǎn)介
自定義View通常分為2類(lèi):自定義View和自定義ViewGroup
1、構(gòu)造函數(shù)
為什么說(shuō)到構(gòu)造函數(shù),因?yàn)椴煌男枨笙挛覀兯枰臉?gòu)造函數(shù)是不同的:
public class CustomView extends View {
/**
* 當(dāng)我們Java代碼里面new的時(shí)候,會(huì)調(diào)用當(dāng)前構(gòu)造函數(shù)
*/
public CustomView(Context context) {
super(context);
}
/**
* 當(dāng)我們?cè)贚ayout中使用View的時(shí)候,會(huì)調(diào)用當(dāng)前構(gòu)造函數(shù)
*
* @param attrs XML屬性(當(dāng)從XML inflate的時(shí)候)
*/
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
/**
* 當(dāng)我們?cè)贚ayout中使用View且使用Style屬性的時(shí)候,會(huì)調(diào)用當(dāng)前構(gòu)造函數(shù)
*
* @param defStyleAttr 應(yīng)用到View的默認(rèn)風(fēng)格(定義在主題中)
*/
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
2、坐標(biāo)
Android坐標(biāo)系與我們常見(jiàn)數(shù)據(jù)中的左邊系不一樣,即左正下正,如圖下所示:

獲取View位置
//獲取View坐標(biāo)
getLeft(); getTop();getBottom();getRight();
//onTouch中 觸摸位置相對(duì)于在組件坐標(biāo)系的坐標(biāo)
event.getX(); event.getY();
//onTouch中 觸摸位置相對(duì)于屏幕默認(rèn)坐標(biāo)系的坐標(biāo)
event.getRawX(); event.getRawY();
3、自定義屬性Attr
在自定義View時(shí),我們經(jīng)常使attr,如我們常常使用的android:layout_xxx屬性,就是定義attr在布局中使用的。自定義Attr流程如下:
-
res/values目錄下新建一個(gè)attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="custom"> <attr name="title" format="string"/> <attr name="size" format="integer"/> </declare-styleable> </resources>format表示了Attr的類(lèi)型:reference:引用某一資源ID;fraction:百分?jǐn)?shù);flag:標(biāo)記位,各個(gè)取值可用“|”連接;其他根據(jù)意思就可以理解了
-
使用自定義屬性
加入命名空間xmlns:你自己定義的名稱(chēng)="http://schemas.android.com/apk/res/你程序的package包名",然后在布局中使用<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res/com.example.active.loser.views .CustomView" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.active.loser.views.CustomView custom:title="cuson_title" custom:size="10" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> -
獲取定義的Attrs的屬性值
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //獲取配置屬性 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.custom, defStyleAttr, defStyleAttr); String title = a.getString(R.styleable.custom_title); int size = a.getInteger(R.styleable.custom_size, 20); //回收資源 a.recycle(); }