1.首先在res/values/attrs.xml文件中,定义declare-styleable
<declare-styleable name="RoundTopLayout">
<attr name="backcolor" format="color"/>
<attr name="linecolor" format="color"/>
<attr name="linesize" format="dimension"/>
<attr name="gapsize" format="dimension"/>
<attr name="centerwidth" format="dimension"/>
declare-styleable>
2.在java文件中获取属性值
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundTopLayout, defStyle, 0);
GapSize = a.getDimension(R.styleable.RoundTopLayout_gapsize, GapSize);
MidWidth = a.getDimension(R.styleable.RoundTopLayout_centerwidth, MidWidth);
Paint_Diameter = a.getDimension(R.styleable.RoundTopLayout_linesize, Paint_Diameter);
LineColor = a.getColor(R.styleable.RoundTopLayout_linecolor, LineColor);
BackColor = a.getColor(R.styleable.RoundTopLayout_backcolor, BackColor);
a.recycle();
3.布局文件自定义命名空间,属性赋值
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:rtl="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<com.danielhan.sample.library.RoundTopLayout
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_alignParentBottom="true"
android:layerType="software"
rtl:centerwidth="70dp"
rtl:gapsize="20dp"
rtl:linecolor="@color/gray_999"
rtl:linesize="1dp">
1.首先在res/values/attrs.xml文件中,定义attr
"roundTopLayoutStyle" format="reference"/>
2.然后再res/values/styles中添加全局属性style,然后引入到项目所用theme中
AndroidManifest.xml 如下,用的是deyangStyle
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/deyangStyle">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>
3.java中使用R.attr.roundTopLayoutStyle
if (attrs != null) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundTopLayout, R.attr.roundTopLayoutStyle, 0);
GapSize = a.getDimension(R.styleable.RoundTopLayout_gapsize, GapSize);
MidWidth = a.getDimension(R.styleable.RoundTopLayout_centerwidth, MidWidth);
Paint_Diameter = a.getDimension(R.styleable.RoundTopLayout_linesize, Paint_Diameter);
LineColor = a.getColor(R.styleable.RoundTopLayout_linecolor, LineColor);
BackColor = a.getColor(R.styleable.RoundTopLayout_backcolor, BackColor);
a.recycle();
}
1.res/values/styles中添加style
2.layout 中使用style
<com.danielhan.sample.library.RoundTopLayout
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_alignParentBottom="true"
android:layerType="software"
style="@style/CustomRoundTopLayoutStyle1">
public void setLineColor(int lineColor) {
this.lineColor = lineColor;
paint.setColor(lineColor);
invalidate();
}
总结,完善的自定义控件,必须提供这四种属性设置方式
代码传送门