自定义组合控件和自定义属性

自定义控件的步骤: 

1、先写一个布局,这里我用的是一个相对布局,我这里的相对布局就是根布局了

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:paddingBottom="10dp"
    android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:paddingTop="10dp" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="设置自动更新"
        android:textColor="#000000"
        android:textSize="16sp" />

    <ImageView
        android:id="@+id/iv_toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/off" />

</RelativeLayout>

2、用一个类去继承这个布局(相对布局),注意一下,这里最好继承这个布局的根布局,因为有可能会用到根布局里的一些属性

   public class SettingItemView extends RelativeLayout{}

3、继承布局的这个类会实现三个构造方法,一般情况下,用到那个就从写那个,但是,如果你不知道要用到那个,那么,你可以三个都实现,通过有一个参数和两个参数的构造方法去调用第三个构造方法,因为第三个构造方法系统并不会自动帮我们调用

自定义属性步骤:

 * 1、在res/values下新建一个attrs.xml

 * 2、在自定义类中通过attrs去获取这些属性

 * 3、在布局文件中使用这些属性时,需要声明命名空间

       注意 xmlns: custom = "http://schemas.android.com/apk/res-auto"
       在需要的地方引用第三方控件的名字空间,custom是自己任意命名的。

取值类型一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;

reference:参考某一资源ID,color:颜色值,boolean:布尔值,dimension:尺寸值,float:浮点值

integer:整型值,string:字符串,fraction:百分数, enum:枚举值, flag:位或运算



猜你喜欢

转载自blog.csdn.net/owen_bland/article/details/79561767