在xml中写出自定义的属性值方法。
实例:在xml中给自定义布局写出自定义属性的值。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<com.zq.androidservice.dialog.SelfView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:text="aaaa"
app:background_color="@color/blue"
/>
xmlns:app="http://schemas.android.com/apk/res-auto" 这一句话是用来命名空间的。前面的app可以随便改成任何你想要的自定义的名字。
1.首先需要你在values的styles中写你想要的属性与属性命名,与你给这些属性集合的命名。(这里是SelfView)
<resources>
<declare-styleable name="SelfView">
<attr name="background_color" format="color"/>
<attr name="text" format="string"/>
</declare-styleable>
</resources>
然后需要你在自定义视图的.java文件中获取绑定,调用AttributeSet的属性获取对应的你在value
private void init(Context context,AttributeSet attrs){
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.SelfView);
int mColor = ta.getColor(R.styleable.SelfView_background_color, Color.BLACK);
String mTextStr = ta.getString(R.styleable.SelfView_text );
ta.recycle(); //注意回收
Log.e("SelfView_text","SelfView_text = " + mTextStr);
}
注意:此方法是需要你自定去手写,在自定义视图的构造器中去调用。获取到你在xml中设置的属性值,然后根据你的需求,做出相对应的处理。
绑定属性时,先是通过属性集的名字,获取属性集。然后是以属性集的名字做前缀,带下划线的形式,接上属性名,获取对应属性值。
之后获取到的属性值拿去做你想做的处理。
至此完毕~