Android自定义控件封装之自定义属性的实现


在开发中有时候我们需要去自定义一些组合控件,而在使用过程中,又想要自己的组合控件能有原生控件那样可以在xml中使用属性控制,那么我们就需要去自定义一些属性了

1:首先在values/attrs.xml中进行属性的定义

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyAppTitle">
        <attr name="TitleText" format="string"/>
        <attr name="LeftText" format="string"/>
        <attr name="RightText" format="string"/>
    </declare-styleable>
    
</resources>

2:在定义好这些属性后,就需要在自己自定义的类中进行获取和操作了

public MyAppTitle(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyAppTitle);
    mLeftText = ta.getString(R.styleable.MyAppTitle_LeftText);
    mTitleText = ta.getString(R.styleable.MyAppTitle_TitleText);
    mRightText = ta.getString(R.styleable.MyAppTitle_RightText);
    Log.e("Fizzer",mLeftText+mRightText+mTitleText);
}

3:接下来就可以在xml文件布局中进行使用了

<com.fizzer.anbangproject_dahuo_test.Widget.MyAppTitle
    android:id="@+id/viewMyAppTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    fizzer:TitleText="标题"
    fizzer:LeftText="左边"
    fizzer:RightText="右边"/>


还有一点要注意的就是,别忘了在根布局中进行命名空间的声明

xmlns:fizzer="http://schemas.android.com/apk/res-auto"


命名空间的名字是可以自定义的,比如文中的“fizzer”,开发者可以自己自行定义,但是在xml文件使用中一定要使用自己定义的命名


4:最后说一点的就是,在attrs文件中styleable中的命名是可以自定义的,但是为了在书写布局文件时有属性的提示功能,所以最好还是保持自定义控件的类名与styleable的命名一致,当然,Google也支持和鼓励开发者使用对应的类名来作为styleable的命名




猜你喜欢

转载自blog.csdn.net/u014697083/article/details/52248791
今日推荐