今天写了一个类继承了View
public CustomView extends View
把View的background设置为黑色
<View
android:layout_width = "100dp"
android:layout_height = "100dp"
android:background = "#ff000000"/>
然后调用mCustomView.scrollby(dx,dy);
发现 这个View 并没有移动,还是在原来的位置。
查了比较久,才发现,在View的onDraw 里面,有这样一段。
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
也就是说,View的background会判断scrollX和ScrollY是否为零,然后把canvas调整为原来的的位置
后来我重写了
public void onDraw(Canvas canvas){
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ff000000"))
canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),paint);
}
终于看到View 的黑色部分偏移了