I wanted to move my button if coordinates of final position are inside my view. So I store initial touch(ACTION_DOWN) in so I can differentiate move from the click, But Something is wrong. My button flying away on move event! and click doesn't work at all. My main goal is to prevent moving button outside view(screen/window).
My guess is that coordinates I get as my view boundary in Outlocation
is misleading or setX()/setY()
consume parameters that have incompatible type compared to pixels I've got.
Here is my Code relative to this matter:
b = (FloatingActionButton) view.findViewById(R.id.fab);
b.setOnTouchListener(new View.OnTouchListener() {
float x, y;
float[] Outlocation = new float[2];
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
float new_x = event.getRawX() ;
float new_y = event.getRawY();
// v.getLocationOnScreen(Outlocation);
DisplayMetrics metrics = getResources().getDisplayMetrics();
Outlocation[0] = metrics.widthPixels;
Outlocation[1] = metrics.heightPixels;
if (new_x > Outlocation[0]) {
new_x = x ;
} else if (new_x < 0) {
new_x = x;
}
if (new_y > Outlocation[1]) {
new_y = y;
} else if (new_y < 0) {
new_y = y;
}
b.setX(b.getX() + (new_x - x));
b.setY(b.getY() + (new_y - y));
return true;
case MotionEvent.ACTION_DOWN:
x = event.getRawX();
y = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
if(x == event.getRawX() & (y == event.getRawY())) {
//Handle Click Event
Intent intent = new Intent(getContext(), AddActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
MainActivity.Gone = true;
MainActivity.setTab = 1;
return true;
}
}
return false;
}
});
Update: Dennis answer won't work because custom layout would cover some part of messages list which is the reason i want to move button in the first place so that user could read part of message behind it.