您的位置:首页 > 移动开发 > Android开发

android自定义样式与View的构造函数

2015-07-29 15:22 495 查看
为了使自定义的View的属性可以在xml中配置,需要以下步骤:

在/res/values中创建attrs.xml文件,通过为自定义View添加属性

[code]<declare-styleable name="RoundedImageView">
        <attr name="corner_radius" format="dimension" />
        <attr name="border_width" format="dimension" />
        <attr name="border_color" format="color" />
        <attr name="mutate_background" format="boolean" />
        <attr name="oval" format="boolean" />
        <attr name="android:scaleType" />
</declare-styleable>


在xml中为自定义属性加上xmlns:app=”http://schemas.android.com/apk/res-auto”或者xmlns:app=”http://schemas.android.com/apk/res/包名”,如果当前工程是作为lib使用,那么必须使用第一种,否则会出现找不到自定义属性的错误。其中app时自定义属性的前缀。

3 . 在xml中为自定义属性声明属性值

[code]<com.mitrader.jinnang.view.imageview.round.RoundedImageView
            android:id="@+id/imageview_menu_user_avatar"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_margin="12dp"
            android:contentDescription="@string/app_name"
            android:scaleType="fitXY"
            android:src="@drawable/ic_face"
            android:textStyle="bold"
            app:border_color="@color/common_color_dark"
            app:border_width="4dp"
            app:oval="true" />


4 在构造函数中获取属性值

[code]public RoundedImageView(Context context, AttributeSet attrs) {      
    this(context, attrs, 0);    
} 
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {        
    super(context, attrs, defStyle);    
    TypedArraya=context.obtainStyledAttributes
        (attrs,R.styleable.RoundedImageView,defStyle,0);    
    cornerRadius = a.getDimensionPixelSize(
            R.styleable.RoundedImageView_corner_radius, -1);        
    borderWidth = a.getDimensionPixelSize(
        R.styleable.RoundedImageView_border_width, -1);
    borderColor = a.getColorStateList
        (R.styleable.RoundedImageView_border_color);            
    mutateBackground = a.getBoolean
        (R.styleable.RoundedImageView_mutate_background, false);        
    isOval = a.getBoolean(R.styleable.RoundedImageView_oval, false);        
    a.recycle();    
}


如果在Code中实例化一个View会调用第一个构造函数RoundedImageView(Context context),如果在xml中定义会调用第二个构造函数RoundedImageView(Context context, AttributeSet attrs),第三个构造函数RoundedImageView(Context context, AttributeSet attrs, int defStyle)系统是不会调用的,要由View显示调用,比如这里使用第二个构造函数调用了第三个构造函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: