转载注明出处:http://blog.csdn.net/lb454048898/article/details/50791101
意义
首先知道自定义View的意义,就是Android自身提供的控件已经满足不了我们的需求的时候就会进行继承View来进行自定义View的代码编写,实现需求。
需求
定义需求,是何种,例如 下拉刷新上拉更多的列表 , 看具体展示内容,可继承 GridView 或者 ListView 。
步骤
一般来说,只需要了解最基本的自定义方法即可。
下面介绍几个最普遍的方法:
OnMeasure (测量控件宽高的方法。)
OnDraw (绘制控件内容的方法)
OnLayout (此方法继承ViewGroup用的较多,用于摆放Group里子view的位置)
正题
- 定义自定义字节属性,此属性是在布局文件xml里View的属性。
- 在View的构造方法中获取属性。
- 重写onMeasure方法
- 重写OnDraw方法
这四个步骤是最常见的步骤。
来看一段ImageView的onMeasure方法。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
resolveUri();
int w;
int h;
// Desired aspect ratio of the view's contents (not including padding)
float desiredAspect = 0.0f;
// We are allowed to change the view's width
boolean resizeWidth = false;
// We are allowed to change the view's height
boolean resizeHeight = false;
final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
if (mDrawable == null) {
// If no drawable, its intrinsic size is 0.
mDrawableWidth = -1;
mDrawableHeight = -1;
w = h = 0;
} else {
w = mDrawableWidth;
h = mDrawableHeight;
if (w <= 0) w = 1;
if (h <= 0) h = 1;
// We are supposed to adjust view bounds to match the aspect
// ratio of our drawable. See if that is possible.
if (mAdjustViewBounds) {
resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
desiredAspect = (float) w / (float) h;
}
}
int pleft = mPaddingLeft;
int pright = mPaddingRight;
int ptop = mPaddingTop;
int pbottom = mPaddingBottom;
int widthSize;
int heightSize;
if (resizeWidth || resizeHeight) {
/* If we get here, it means we want to resize to match the
drawables aspect ratio, and we have the freedom to change at
least one dimension.
*/
// Get the max possible width given our constraints
widthSize = resolveAdjustedSize(w + pleft + pright, mMaxWidth, widthMeasureSpec);
// Get the max possible height given our constraints
heightSize = resolveAdjustedSize(h + ptop + pbottom, mMaxHeight, heightMeasureSpec);
if (desiredAspect != 0.0f) {
<