我有一个带有两个图像视图的活动,例如:example。创建活动时,第一个活动开始从屏幕左侧移动到右侧(第二个图像视图不移动),我想检测一下当第一个图像视图是否在第二个图像视图的范围内时用户是否触摸屏幕。
我尝试编写此代码:(homeLayout是包含2个图像的布局)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ButterKnife.bind(this);
homeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
homeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
image2.getLocationOnScreen(locations);
xImage2 = locations[0];
}
});
homeLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float xCurrentPos = image1.getLeft();
if (xCurrentPos >= xImage2 && (xCurrentPos <= xImage2 + image2.getWidth())) {
inRange = true;
}
if (inRange) {
Toast.makeText(getApplicationContext(), "In range", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Out of range", Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
我的问题是我弄错了image1的当前x位置,因此布尔inRange总是错误的,得到“超出范围”吐司消息。
当用户触摸屏幕时,如何获取image1的当前x位置并检查image1是否在image2的范围内?
我被卡住了,无法解决。
最佳答案
经过几个小时的搜索,我设法使用以下代码检索了运动图像的当前x位置:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ButterKnife.bind(this);
homeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
homeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
image2.getLocationOnScreen(locations);
xImage2 = locations[0];
}
});
ObjectAnimator translateXAnimation = ObjectAnimator.ofFloat(image1, "translationX", image1.getLeft(), xFinalPos);
translateXAnimation.setDuration(4000);
translateXAnimation.start();
translateXAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
xCurrentPos = (float)valueAnimator.getAnimatedValue();
}
});
homeLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (xCurrentPos >= xImage2 && (xCurrentPos <= xImage2 + image2.getWidth())) {
inRange = true;
}
if (inRange) {
Toast.makeText(getApplicationContext(), "In range", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Out of range", Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
我必须使用AnimatorUpdateListener才能收回运动图像的当前x位置