我们知道ScrollTo(int x,int y)、ScrollY(int x,int y)不会改变View本身的位置,但是可以改变子View和本身内容(onDraw中绘制的东西)的位置,口说无凭,下面用一个例子来说明
MyView.java
public class MyView extends ViewGroup { Paint paint; public MyView(Context context) { this(context, null); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); paint=new Paint(); paint.setColor(Color.GREEN); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(10); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measureChildren(widthMeasureSpec,heightMeasureSpec); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int chidCount=getChildCount(); for(int i=0;i<chidCount;i++) { View child=getChildAt(i); child.layout(0,0,child.getMeasuredWidth(),child.getMeasuredHeight()); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawRect(200,200,300,300,paint); } }
package com.solo.text; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { MyView v1; Button bt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); v1=(MyView)findViewById(R.id.id_v1); bt=(Button)findViewById(R.id.id_bt); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v1.scrollBy(-50,-50); } }); } }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <com.solo.text.MyView android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:id="@+id/id_v1" android:background="#ffc1ffff" android:layout_width="300dp" android:layout_height="400dp" > <View android:background="#ffff0c09" android:layout_width="50dp" android:layout_height="50dp"/> </com.solo.text.MyView> <Button android:id="@+id/id_bt" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="Scroll"/> </RelativeLayout>
跟我们上面分析的结果一样,红色的子view和绿色的本身内容都改变了位置
我们知道scrollTo和scrollBy会改变view的mScrollX和mScrollY的值
我曾经做个一个测试,发现view.draw(Canvas canvas)中canva的边界为mScrollX,mScrollY,mScrollX+mWidth,mScrollY+mHeight;
设view的边界为(cl,ct,cr,cb),view的父容器为parent,parent的mScrollX=sx,mScrollY=sy
1、当sx=sy=0时,view在parent的位置如图所示:
2、当sx=sy=-50时,view在parent的位置如图所示:
对比上面两幅图我们可以看出,view在parent中的位置移动了(-mScrollX,-mScrollY)