自定义控件

参考:http://www.cnblogs.com/bill-joy/archive/2012/04/26/2471831.html

Android 深入理解Android中的自定义属性

1.在res/values目录下新建任意文件名xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TestMySelfTextView">
        <attr name="myTextColor" format="color"></attr>
        <attr name="myTextSize" format="dimension" />

    </declare-styleable>
</resources>

2.新建Java类,继承View:

public class TestMySelfTextView extends View {
    private Context mContext;
    private Paint mPaint;

    public TestMySelfTextView(Context context) {
        super(context);
        this.mContext = context;
        this.mPaint = new Paint();
        Log.d("pepelu", " super(context);");
    }

    /**
     * 默认走这个构造器
     *
     * @param context
     * @param attrs
     */
    public TestMySelfTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Log.d("pepelu", " super(context, attrs)");
        this.mContext = context;
        this.mPaint = new Paint();
        //TypedArray是一个用来存放由context.obtainStyledAttributes获得的属性的数组,在使用完成后,一定要调用recycle方法
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TestMySelfTextView);
        //属性的名称是styleable中的名称+“_”+属性名称
        int textColor = array.getColor(R.styleable.TestMySelfTextView_myTextColor, 0XFF00FF00);//提供默认值
        float textSize = array.getDimension(R.styleable.TestMySelfTextView_myTextSize, 36);
        mPaint.setColor(textColor);
        mPaint.setTextSize(textSize);
        array.recycle();//一定要调用,否则这次的设定会对下次的使用造成影响

    }

    public TestMySelfTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        Log.d("pepelu", " super(context, attrs, defStyleAttr)");
        this.mContext = context;
        this.mPaint = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawRect(10, 10, 100, 100, mPaint);
        mPaint.setColor(Color.BLUE);
        canvas.drawText("well well well", 10, 120, mPaint);
    }
}

3.配置layout文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:pepelu="http://schemas.android.com/apk/res/com.bojoy.bjsdk_mainland_new"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.widget.TestMySelfTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        pepelu:myTextColor="#000000"
        pepelu:myTextSize="36dp" />

</LinearLayout>
xmlns:pepelu="http://schemas.android.com/apk/res/com.bojoy.bjsdk_mainland_new" ,
pepelu 相当于命名空间,可取任意名,
com.bojoy.bjsdk_mainland_new:是包名
pepelu:myTextColor在该命名空间下。java中的相应值也是在这里取。

原文地址:https://www.cnblogs.com/mada0/p/5099689.html