弘扬博客
自定义View的步骤:
1、自定义View的属性
2、在View的构造方法中获得我们自定义的属性
[ 3、重写onMesure ]
4、重写onDraw
1、自定义View的属性,首先在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式。
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
-
- <attr name="titleText" format="string" />
- <attr name="titleTextColor" format="color" />
- <attr name="titleTextSize" format="dimension" />
-
- <declare-styleable name="CustomTitleView">
- <attr name="titleText" />
- <attr name="titleTextColor" />
- <attr name="titleTextSize" />
- </declare-styleable>
-
- </resources>
我们定义了字体,字体颜色,字体大小3个属性,format是值该属性的取值类型:
一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;不清楚的可以google一把。
然后在布局中声明我们的自定义View
然后在布局中声明我们的自定义View
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <com.example.customview01.view.CustomTitleView
- android:layout_width="200dp"
- android:layout_height="100dp"
- custom:titleText="3712"
- custom:titleTextColor="#ff0000"
- custom:titleTextSize="40sp" />
-
- </RelativeLayout>
一定要引入 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"我们的命名空间,后面的包路径指的是项目的package
2、在View的构造方法中,获得我们的自定义的样式
-
-
-
- private String mTitleText;
-
-
-
- private int mTitleTextColor;
-
-
-
- private int mTitleTextSize;
-
-
-
-
- private Rect mBound;
- private Paint mPaint;
-
- public CustomTitleView(Context context, AttributeSet attrs)
- {
- this(context, attrs, 0);
- }
-
- public CustomTitleView(Context context)
- {
- this(context, null);
- }
-
-
-
-
-
-
-
-
- public CustomTitleView(Context context, AttributeSet attrs, int defStyle)
- {
- super(context, attrs, defStyle);
-
-
-
- TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);
- int n = a.getIndexCount();
- for (int i = 0; i < n; i++)
- {
- int attr = a.getIndex(i);
- switch (attr)
- {
- case R.styleable.CustomTitleView_titleText:
- mTitleText = a.getString(attr);
- break;
- case R.styleable.CustomTitleView_titleTextColor:
-
- mTitleTextColor = a.getColor(attr, Color.BLACK);
- break;
- case R.styleable.CustomTitleView_titleTextSize:
-
- mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
- TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
- break;
-
- }
-
- }
- a.recycle();
-
-
-
-
- mPaint = new Paint();
- mPaint.setTextSize(mTitleTextSize);
-
- mBound = new Rect();
- mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
-
- }