android view中有layout(int l, int t, int r, int b) 和offsetTopAndBottom(int offset)和offsetLeftAndRight(int offset) 3个方法,可以用来操作view的位置,下面我们来移动一个view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/ll" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button"/>
<com.test.gesture.TestView
android:id="@+id/tv"
android:layout_gravity="center"
android:layout_width="70dp"
android:layout_height="400dp"
android:background="@android:color/white"
android:text="adfsdfffffffffffffffffffffffffffffffffffff"
android:textColor="@android:color/black"
/>
</LinearLayout>
public class Test_gestureActivity extends Activity {
private Button button;
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.btn);
tv = (TextView) findViewById(R.id.tv);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
button.offsetTopAndBottom(10);
button.offsetLeftAndRight(10);
// button.layout(120, 120, 240, 200);
}
});
}
}

当点击按钮的时候的时候 按钮就会朝右下角的方向慢慢移动并且会压在id为tv的view上,如果tv放在上面,那么tv就会压在按钮之上,同样适用layout也可以达到这样的效果,不过事先一定要计算一下4条边的坐标,用起来有点麻烦。
接下面我们要试试自定义view中的画布的移动,画布不管怎么移动,view是不会移动的,是固定的,我们可以想象画布canvas是无限大的,我们可以根据自己的需求任意的移动。我们通过使用GestureDetector,并且在view的onTouchEvent方法中截断触摸事件并传给gestureDetector的实例,这个类实际上是通过一些算法来判断用户具体是执行什么样的操作,然后我们可以在这些回调方法中执行我们想要做的事情,我们在onDraw里 移动了画布,并在onScroll方法中不断的改变scrollingOffset并且不断的invalidate迫使onDraw方法被不断的调用以此来刷新view的显示效果。这样当你用手在view上上下滑动的时候,感觉里面的字也跟着你的手在动了
public class TestView extends TextView {
private GestureDetector gd;
private int scrollingOffset;
public TestView(Context context, AttributeSet attrs) {
super(context, attrs);
gd = new GestureDetector(context, new InnerGestureListener());
}
@Override
protected void onDraw(Canvas canvas) {
canvas.translate(0, scrollingOffset);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return gd.onTouchEvent(event);
}
class InnerGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
scrollingOffset += -distanceY;
invalidate();
return super.onScroll(e1, e2, distanceX, distanceY);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return super.onFling(e1, e2, velocityX, velocityY);
}
}
}