【发布时间】:2017-10-16 12:15:49
【问题描述】:
我有 FrameLayout 封装了两个 ImageViews。这是我想要的:
在用户触摸和拖动时移动整个布局,但当点击时,应由个人ImageViews(通过他们各自的View.OnClickListener())处理
当前行为: 目前,当我尝试拖动视图组时,它会随机跳转一次(每个拖动事件),然后开始用手指移动。因此,就像您将手指移到视图组外,它也在移动。
其次,没有点击事件被路由到子ImageViews
我尝试过的:
我已尝试扩展封装ImageViews 的FrameLayout:
public class ChatHeadFrameLayout extends FrameLayout {
/**
* Store the initial touch down x coordinate
*/
private float initialTouchX;
/**
* Store the initial touch down y coordinate
*/
private float initialTouchY;
public ChatHeadFrameLayout(@NonNull Context context) {
super(context);
}
public ChatHeadFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ChatHeadFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(21)
public ChatHeadFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// If the event is a move, the ViewGroup needs to handle it and return
// the indication here
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//remember the initial position
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Will be called in case we decide to intercept the event
// Handle the view move-with-touch behavior here
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//remember the initial position
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
int Xdiff = (int) (event.getRawX() - initialTouchX);
int Ydiff = (int) (event.getRawY() - initialTouchY);
//The check for Xdiff <10 && YDiff< 10 because sometime elements moves a little while clicking.
//So that is click event.
if (Xdiff < 10 && Ydiff < 10) {
return false;
}
return true;
case MotionEvent.ACTION_MOVE:
//Calculate the X and Y coordinates of the view.
setX(event.getRawX() - initialTouchX);
setY(event.getRawY() - initialTouchY);
//Update the layout with new X & Y coordinate
invalidate();
return true;
}
return false;
}
}
那么,这段代码有什么问题?
【问题讨论】:
标签: android