MyCustomView
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import com.tencent.formalandroid.R;
public class MyCustomView extends View {
private int mBackgroudColor;
// 仿照Scrollview去书写
public MyCustomView(Context context) {
this(context, null);
}
public MyCustomView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attributeSets) {
// 获取自定义属性的数组
TypedArray typedArray = context.obtainStyledAttributes(attributeSets, R.styleable.MyCustomView);
// 拿到自定义的颜色
mBackgroudColor = typedArray.getColor(R.styleable.MyCustomView_backgroundColor, Color.RED);
// 给自身赋值
this.setBackgroundColor(mBackgroudColor);
}
}
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="backgroundColor" format="color"/>
</declare-styleable>
</resources>
使用:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
// 注意:这里一定要加上这句话,引入新的命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
// 这里,需要加上包名+路径
<com.tencent.formalandroid.view.MyCustomView
android:layout_width="200dp"
android:layout_height="100dp"/>
</LinearLayout>
网友评论