背景
之前講了Android自定義View實現圓形效果,但是很簡單,并沒有實現一些自定義的屬性,今天就大致實現以下自定義屬性。
自定義屬性
我們在布局文件里面可以寫一些以android開頭的屬性,這些都是系統的自帶屬性,我們也可以定義一些自己的。
- 在valuse目錄下面創建一些自定義屬性的XML,比如attrs.xml,也可以是arrts_circle.xml,只要以arrts開頭就可以,沒有什么特殊要求,比如:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CircleView"> <attr name="circle_color" format="color" /> </declare-styleable> </resources>
上面定義了一個自定義的屬性集"CircleView",在這個集合里面也可以有多種自定義屬性,我們只是制定了顏色,其中format可以有多種格式,color表示的是顏色,其他的reference表示資源Id,dimension表示尺寸大小,string,integer,boolean表示的是基本數據類型,等等。 - 在自定義View的構造方法里面解析自定義屬性的值并作相應的處理,在我們之前的代碼里面只要修改構造方法就可以:
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArrayarray = context.obtainStyledAttributes(attrs,R.styleable.CircleView); mColor = array.getColor(R.styleable.CircleView_circle_color,Color.GREEN); array.recycle(); init(); }
- 我們只要在布局里面設置顏色值就可以了
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <com.aotuman.circleview.view.CircleView android:padding="10dp" android:layout_margin="10dp" android:layout_width="wrap_content" android:layout_height="200dp" app:circle_color="@color/colorAccent" android:background="@android:color/black"/> </RelativeLayout>
大家需要注意的是,我不只是加了一行修改顏色的代碼,除了
app:circle_color="@color/colorAccent"
之外還有下面這一行也是必須的:
xmlns:app="http://schemas.android.com/apk/res-auto"
結尾
好了,到這里為止,我們簡單的自定義屬性也已經完成了,我們來看一下自定義顏色的效果圖
自定義顏色