Android自定义属性

2023-05-19,,

1   定义属性如下:

    <resources>

    

        <declare-styleable name="social_ivAndTv">

            <attr name="p_w_picpathResource" format="integer" />

            <attr name="title" format="string" />

        </declare-styleable>

    

    </resources>

2 在自定义组件中引用(加粗字体):

        

public ImageViewAndTextView(Context context, AttributeSet attrs) {

super(context, attrs);

     TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.social_ivAndTv);

     resourceId = array.getResourceId(R.styleable.social_ivAndTv_p_w_picpathResource, 0);

     content = array.getString(R.styleable.social_ivAndTv_title);

     initView(context);

}

3 在布局文件中引用:

        3.1在顶部添加命名空间:

                xmlns:app="http://schemas.android.com/apk/res/包名"

        3.2 在自定义组建中添加自定义属性:               

                app:p_w_picpathResource="@drawable/socialweibo_icon_neutral_normal"

                app:title="正面" 

4 完成工作。

《Android自定义属性.doc》

下载本文的Word格式文档,以方便收藏与打印。