android中经常需要用到自定义控件,有时候还需要自己定义attrs,我贴出一点自己的理解。
首先,写一个declare-styleable(如果没有attrs文件,就自己建一个;这里用的是Android v7包中自带的CardView的attrs):
<span style="font-size:18px;"><resources>
<declare-styleable name="CardView">
<!-- Background color for CardView. -->
<attr name="cardBackgroundColor" format="color" />
<!-- Corner radius for CardView. -->
<attr name="cardCornerRadius" format="dimension" />
<!-- Elevation for CardView. -->
<attr name="cardElevation" format="dimension" />
<!-- Maximum Elevation for CardView. -->
<attr name="cardMaxElevation" format="dimension" />
<!-- Add padding in API v21+ as well to have the same measurements with previous versions. -->
<attr name="cardUseCompatPadding" format="boolean" />
<!-- Add padding to CardView on v20 and before to prevent intersections between the Card content and rounded corners. -->
<attr name="cardPreventCornerOverlap" format="boolean" />
<!-- Inner padding between the edges of the Card and children of the CardView. -->
<attr name="contentPadding" format="dimension" />
<!-- Inner padding between the left edge of the Card and children of the CardView. -->
<attr name="contentPaddingLeft" format="dimension" />
<!-- Inner padding between the right edge of the Card and children of the CardView. -->
<attr name="contentPaddingRight" format="dimension" />
<!-- Inner padding between the top edge of the Card and children of the CardView. -->
<attr name="contentPaddingTop" format="dimension" />
<!-- Inner padding between the bottom edge of the Card and children of the CardView. -->
<attr name="contentPaddingBottom" format="dimension" />
</declare-styleable>
</resources></span>
其次,在xml中加入,如:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:db="http://schemas.android.com/apk/res/com.attrs.demo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<span style="color:#ffff00;">db:cardCornerRadius="8dp"</span> >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="kdddddddddddsl" />
</android.support.v7.widget.CardView>
</LinearLayout>
其中红色部分( xmlns:db那行)就是在给自己的attrs注册,紫色的db是name,可以自己随便写,后面绿色的(com.attrs.demo)是包名,自己的程序包名。
最后使用时就按黄色部分写出就行。
注:发上去后才发现颜色标注真让人蛋疼,又人工标注了。