ボタンをActivity画面でドラッグ、配置
2324 ワード
private ImageView img1;
private int screenWidth;
private int screenHeight;
@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);
img1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println(333333);
Toast.makeText(RemoveImageActivity.this, " ", Toast.LENGTH_SHORT).show();
}
});
}
private OnTouchListener movingEventListener = new OnTouchListener() {
int lastX, lastY;
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == event.ACTION_DOWN) {
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
System.out.println(11111);
}
if (event.getAction() == event.ACTION_MOVE) {
System.out.println(222222);
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();
}
return true;
}
};
どのように値がTRUEに戻るか、ボタンにクリックイベントがある場合、クリックイベントは失効します(傍受できません).
戻り値がFALSEの場合.では、ドラッグイベントが終了すると、すぐにクリックイベントが実行されます