public MyRect(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int color = ta.getColor(R.styleable.MyView_rect_color, 0xffff0000);
setBackgroundColor(color);
ta.recycle();
}
public MyRect(Context context) {
super(context);
}
}
attrs文件内容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="rect_color" format="color"/>
</declare-styleable>
</resources>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:jkxy="http://schemas.android.com/apk/res/com.jikexueyuan.myrect"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.jikexueyuan.myrect.MyRect
android:layout_width="100dp"
android:layout_height="100dp"
jkxy:rect_color="#ff00ff00"
/>
</LinearLayout>
自定义按钮样式代码如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="false" android:drawable="@drawable/btn_normal"></item>
<item android:state_pressed="true" android:drawable="@drawable/btn_pressed"></item>
</selector>