最近要实现一个自定义scrollview,然后在完成后发现滑动时并不是预期的效果,检查了很多次代码都没有发现bug(确保ontouchevent()方法正确)
折腾了两个多小时,特此记录,以示后人
首先看一下系统一般自定义view时习惯写的构造函数
public Song(Context context) {
this(context,null);
}
public Song(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public Song(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a =context.getTheme().obtainStyledAttributes(attrs, R.styleable.song, defStyleAttr, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.song_text:
text = a.getString(attr);
break;
case R.styleable.song_textsize:
textSize = a.getDimensionPixelSize(attr, (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())
);
break;
case R.styleable.song_textcolor:
textColor = a.getColor(attr, Color.YELLOW);
break;
case R.styleable.song_cricleRadius:
cricleR = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
20,getResources().getDisplayMetrics()
));
break;
}
}
a.recycle();
mContext = context;
mPaint = new Paint();
Log.d("mPaint",mPaint.toString());
mPaint.setColor(textColor);
}
简单来说就是一参调用二参数,二参调用三参,本人在自定义view的时候也是习惯性的这么写,已经到了顺手拈来的地步,但是看一下scrollview的构造函数
public ScrollView(Context context) {
this(context, null);
}
public ScrollView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.scrollViewStyle);
}
public ScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
看到了吧。人家二参调用三参的时候有传入defStyleAttr,知道哪里错了吧,
所以以后再使用this的时候的小心点儿了