- public class TestDemo extends Activity {
- private ImageView img1;
- private int screenWidth;
- private int screenHeight;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- img1 = (ImageView) findViewById(R.id.imageView1);
- DisplayMetrics dm = getResources().getDisplayMetrics();
- screenWidth = dm.widthPixels;
- screenHeight = dm.heightPixels - 50;
- img1.setOnTouchListener(movingEventListener);
- }
- private OnTouchListener movingEventListener = new OnTouchListener() {
- int lastX, lastY;
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- lastX = (int) event.getRawX();
- lastY = (int) event.getRawY();
- break;
- case MotionEvent.ACTION_MOVE:
- int dx = (int) event.getRawX() - lastX;
- int dy = (int) event.getRawY() - lastY;
- int left = v.getLeft() + dx;
- int top = v.getTop() + dy;
- int right = v.getRight() + dx;
- int bottom = v.getBottom() + dy;
- // 设置不能出界
- if (left < 0) {
- left = 0;
- right = left + v.getWidth();
- }
- if (right > screenWidth) {
- right = screenWidth;
- left = right - v.getWidth();
- }
- if (top < 0) {
- top = 0;
- bottom = top + v.getHeight();
- }
- if (bottom > screenHeight) {
- bottom = screenHeight;
- top = bottom - v.getHeight();
- }
- v.layout(left, top, right, bottom);
- lastX = (int) event.getRawX();
- lastY = (int) event.getRawY();
- break;
- case MotionEvent.ACTION_UP:
- break;
- }
- return true;
- }
XML布局
<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" >
<ImageView
android:id="@+id/show_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/a" />
</RelativeLayout>
其中 在onTouch 代码中 如果返回 false 就不能捕捉到ACTION_MOVE 事件。
对于onTouchEvent 中onTouch返回值
1 、如果return false 说明还没有消费onTouch事件,在执行onTouch里代码后,onTouch事件并没有结束。
2、如果return true 说明消费了onTouch事件 onTouch事件结束了
但在实际操作中 除了ACTION_DOWN事件以外,其余的事件只有返回true的那个方法才能捕捉到。所以 返回false的时候只能捕捉到每次的第一个DOWN事件 后面的MOVE 和UP事件就捕捉不到了。
时间: 2024-10-06 15:10:35