1、在values文件夹下新建自己的属性文件myView_attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyViewStyle"> <attr name="bg_color" format="color" /> </declare-styleable> </resources>
定义自己想要的属性.,类型有这些。
2、在xml中使用
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bruce="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.supermap.myapplication.MainActivity"> <com.supermap.myapplication.MyView android:layout_width="match_parent" android:layout_height="match_parent" bruce:bg_color="@color/colorPrimaryDark" /> </LinearLayout>这里使用自己的命名空间。使用别名bruce或者其他的。
3、在view中获取自己定义的属性的值
private void getAttrs(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyViewStyle); if (typedArray != null) { backgroundColor = typedArray.getColor(R.styleable.MyViewStyle_bg_color, Color.WHITE); typedArray.recycle(); } }
完整代码为:
package com.supermap.myapplication; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Created by Administrator on 2017/6/5 0005. */ public class MyView extends View { private int backgroundColor = Color.WHITE; 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); initCommon(context, attrs); } /** * 得到自定义的属性和初始化常用工具 * * @param context * @param attrs */ private void initCommon(Context context, AttributeSet attrs) { getAttrs(context, attrs); } private void getAttrs(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyViewStyle); if (typedArray != null) { backgroundColor = typedArray.getColor(R.styleable.MyViewStyle_bg_color, Color.WHITE); typedArray.recycle(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } @Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(backgroundColor); } }