. 创建 MyRect 类 继承View ,这样就可以 在layout 下的XML 文件中定义;
/**
* 如果我们想自定义视图的话,我们得需要创建一个类继承自View,用View呈现一个长方形
*/
public class MyRext extends View {
//这个构造方法是资源解析程序使用的使用的 -只要把组件放到xml文件里面就会执行这个方法。
//它有一个返回值,TypedArray .使用obtainStyledAttributes把attrs传进来第二个参数是所绑定的View
public MyRext(Context context,@Nullable AttributeSet attrs) {
super(context,attrs);
System.out.println("走了这一句");
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyView);
setBackgroundColor(ta.getColor(R.styleable.MyView_rect_color,0xffff0000));
ta.recycle();
}
//这个构造方法是代码进行使用的。
public MyRext(Context context) {
super(context);
}
}
. 自定义的MyRect 的视图 布局。
<com.wxb.wxb.customview.MyRext
android:layout_width="100dp"
android:layout_height="100dp"
wxb:rect_color = "#ff0000ff"
/>
.增加 视图的属性,可以在values 下 新建xml 文件。
<?xml version="1.0"encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="rect_color"format="color"/>
</declare-styleable>
</resources>
. 给MyRect 赋值 ,需要写一个自定义的命名空间,
<?xml version="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:wxb="http://schemas.android.com/apk/res/com.wxb.wxb.customview"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.wxb.wxb.customview.MainActivity">
<com.wxb.wxb.customview.MyRext
android:layout_width="100dp"
android:layout_height="100dp"
wxb:rect_color ="#ff0000ff"
/>
</LinearLayout>