一艳汽、簡介
自定義View通常分為2類:自定義View和自定義ViewGroup
1、構(gòu)造函數(shù)
為什么說到構(gòu)造函數(shù)对雪,因為不同的需求下我們所需要的構(gòu)造函數(shù)是不同的:
public class CustomView extends View {
/**
* 當我們Java代碼里面new的時候河狐,會調(diào)用當前構(gòu)造函數(shù)
*/
public CustomView(Context context) {
super(context);
}
/**
* 當我們在Layout中使用View的時候,會調(diào)用當前構(gòu)造函數(shù)
*
* @param attrs XML屬性(當從XML inflate的時候)
*/
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
/**
* 當我們在Layout中使用View且使用Style屬性的時候,會調(diào)用當前構(gòu)造函數(shù)
*
* @param defStyleAttr 應用到View的默認風格(定義在主題中)
*/
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
2甚牲、坐標
Android坐標系與我們常見數(shù)據(jù)中的左邊系不一樣义郑,即左正下正蝶柿,如圖下所示:
獲取View位置
//獲取View坐標
getLeft(); getTop()丈钙;getBottom();getRight();
//onTouch中 觸摸位置相對于在組件坐標系的坐標
event.getX(); event.getY();
//onTouch中 觸摸位置相對于屏幕默認坐標系的坐標
event.getRawX(); event.getRawY();
3、自定義屬性Attr
在自定義View時交汤,我們經(jīng)常使attr雏赦,如我們常常使用的android:layout_xxx
屬性,就是定義attr在布局中使用的芙扎。自定義Attr流程如下:
-
res/values目錄下新建一個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的類型:reference:引用某一資源ID星岗;fraction:百分數(shù);flag:標記位戒洼,各個取值可用“|”連接俏橘;其他根據(jù)意思就可以理解了
-
使用自定義屬性
加入命名空間xmlns:你自己定義的名稱="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(); }