Android中经常用到自定义view,既然用了自定义view那就不得不提自定义属性。你是否思考过为什么我们在xml文件中进行布局时可以直接通过android:layout_width="match_parent"就可以设置控件的宽度呢?不只是宽度,几乎控件的所有属性都可以在xml文件中进行设置,这是怎样实现的呢,this is a question
``` <attr name="mHeight" format="integer"/>```name就是自定义的属性的名字(比如系统控件的android:layout_width) format 就是属性的类型,这里支持10种类型,常用的有string,integer,boolean等等,这次我们用到了整形,枚举和布尔 注意:我们在自定义属性的名字的时候不能与系统的名字冲突,否则会报错
3,新建一个类继承View类,实现3个构造方法,然后获取我们自定义的属性 ``` java public class MyView extends View { private static final String TAG = "MyView"; private int heiget; private int width; private String name; private int sex; private boolean student; public MyView(Context context) { this(context,null); }
public MyView(Context context, AttributeSet attrs) { this(context, attrs,0); }
public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.burce); heiget=array.getInt(R.styleable.burce_mHeight,0); width=array.getInt(R.styleable.burce_mWidth,0); name=array.getString(R.styleable.burce_mName); sex=array.getInt(R.styleable.burce_sex,0); student=array.getBoolean(R.styleable.burce_student,true); array.recycle();