import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "move_images_by_touch";
private ImageView ivImages;
private LinearLayout root;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//利用布局资源文件设置用户界面
setContentView(R.layout.activity_main);
//通过资源标识符获取控件实例
ivImages = findViewById(R.id.ivImages);
root = findViewById(R.id.root);
//设置根布局可以获取焦点
root.setFocusable(true);
//让布局获取焦点
root.requestFocus();
//给根布局注册完触摸监听器,实现触摸监听器接口,编写触摸事件代码
root.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
//根据触摸动作执行不同的操作
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: //触点按下
Log.d(TAG, "ACTION_DOWN"+event.getX() + "," + event.getY());
break;
case MotionEvent.ACTION_MOVE: //触点移动
Log.d(TAG, "ACTION_MOVE"+event.getX() + "," + event.getY());
break;
case MotionEvent.ACTION_UP: //触点放开
Log.d(TAG, "ACTION_UP"+event.getX() + "," + event.getY());
break;
}
//设置图像控件坐标
ivImages.setX(event.getX()-ivImages.getWidth()/2);
ivImages.setY(event.getY()-ivImages.getHeight()/2);
return true;//设置为真,三个事件:down-->move-->up依次执行
}
});
}
}
|