<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<!-- declare CustomView2 style -->
<declare-styleable name="CustomView2">
<attr name="textColor" format="color" />
<attr name="backgroundColor" format="color" />
</declare-styleable>
</resources>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res/com.gaoyuan4122.customui"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tv_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<com.gaoyuan4122.customui.views.CustomView1
android:id="@+id/cv_custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_hello" />
<TextView
android:id="@+id/tv_hello2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:layout_below="@id/cv_custom1" />
<com.gaoyuan4122.customui.views.CustomView2
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_hello2"
app:backgroundColor="#ff00ff"
app:textColor="#ffff00" />
</RelativeLayout>
private int mTextColor;
private int mBackgroundColor;
public CustomView2(Context context) {
this(context, null);
}
public CustomView2(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView2(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// 通过下面的方法去除自定义属性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView2);
mTextColor = typedArray.getColor(R.styleable.CustomView2_textColor, Color.RED);
mBackgroundColor = typedArray.getColor(R.styleable.CustomView2_backgroundColor, Color.BLUE);
// 最后一定要注意调用这个方法, 至于为什么后面会说.
typedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setStyle(Style.FILL);
mPaint.setColor(mBackgroundColor);
mRect.set(0, 0, 100, 100);
canvas.drawRect(mRect, mPaint);
mPaint.setColor(mTextColor);
mPaint.setTextSize(30.0f);
canvas.drawText("Hello!", 0, 100, mPaint);
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。