View 的scrollTo 和scrollBy

我们的View都有一个绘画层,这个层是没有边界的,如下图所示:

我们有如下的一个小程序,我们先来看下它的一个表现:

先看看它的布局main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"> 
<TextView 
android:id="@+id/txt"
android:layout_width="300dip"
android:layout_height="120dip"
android:text="textview" /> 
<Button 
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button" /> 
</LinearLayout>

注意看我们的代码:

protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
button=(Button) findViewById(R.id.btn); 
textView=(TextView) findViewById(R.id.txt); 
button.setOnClickListener(new View.OnClickListener() { 
@Override 
public void onClick(View v) { 
textView.scrollTo(-200, -100); 
} 
}); 
}

执行代码效果如下:

这里用的是scrollTo方法,它是相对于我们的右上角来说的, 它相对于左上角是(200,100),而我们写的时候,我们就需要写成负数形式才可以生效,这也是我们需要注意的地方。

总结:

1.

scrollTo让我们的layout视图相对于屏幕的左上角进行偏移;

scrollBy是相当于我们当前的坐标进行偏移,我们上面的例子如果改成scrollBy的话,这个TextView文字会不断地向右下角移动,多 次后我 们就不看不到这个TextView的内容了,因为它已经进行了非Layout视图区,而如果我们用scrollTo的话,不管点多少次按钮,它永 远就就 上面显示的那个位置。

2.

如果想要让控件的View视图的内容向右下角移动,我们需要设置的值是负值,而非正值,向左上方向移动是正值,这一点需要我们注意:

如上面的例子中我们让TextView的内容向右下移动的时候,我们的操作是:textView.scrollTo(-200, -100);